2012-04-21 56 views
1

我使用兩個文件在C++中編寫程序。命名空間中的「字符串不是類型」

main.cpp

#include "var.hpp" 
#include <iostream> 
using namespace std; 
using namespace YU; 

int main() 
{ 
    string god = "THL"; 
    age = 10; 
    cout << age << endl; 
    cout << god << endl; 
    return 0; 
} 

var.hpp

#ifndef __VAR_H__ 
#define __VAR_H__ 

#include <string> 

namespace YU 
{ 
    int age; 
    string name; 
} 

#endif 

當我compilered它,It'get錯誤。

錯誤的信息來源是:

In file included from main.cpp:1:0:

var.hpp:9:5: Error: ‘string’ is not a type name

我不知道爲什麼,我只好include <string>頭文件,但它仍然這麼想的工作。

我寫這段代碼只是爲了練習,而不是爲了工作。

謝謝!

回答

4

問題是string的命名空間在var.hppstringstd命名空間,但你不告訴編譯器。你可以通過把using namespace std;var.hpp修復它,但下面是一個更好的解決方案,因爲它不從std混亂與其他事物的全局命名空間:

#ifndef __VAR_H__ 
#define __VAR_H__ 

#include <string> 

namespace YU 
{ 
    int age; 
    std::string name; 
} 

#endif 
+0

+1我太慢了。 – chris 2012-04-21 04:13:43

1

你在你的.cpp文件有using namespace std;,但它在包括var.h之後。如果你要寫這樣的頭文件,你也應該在頭文件中加入using namespace std;

1

Alternativly你可以使用

using std::string; 

這避免了在每個字符串前鍵入的std :: string,你不搶一切從全局命名空間。

相關問題