2011-02-04 410 views
5

我是C++的新手,但我無法弄清楚爲什麼這不會爲我編譯。我在Mac上運行,使用Xcode編碼,但是我正在用自己的makefile編譯bash。C++ g ++在類頭文件中找不到'string'類型

無論如何,我收到了兩個編譯器錯誤,即「包含」時找不到「字符串」類型。任何幫助將受到歡迎。代碼:

//#include <string> // I've tried it here, too. I'm foggy on include semantics, but I think it should be safe inside the current preprocessor "branch" 
#ifndef APPCONTROLLER_H 
#define APPCONTROLLER_H 

#include <string> 
class AppController { 
// etc. 
public: 
    int processInputEvents(string input); //error: ‘string’ has not been declared 
    string prompt(); //error: ‘string’ does not name a type 
}; 
#endif 

我包括我的main.cpp這個文件,並在其他地方我主要使用string類型和它工作得很好。雖然主要我已經包括iostream而不是string(用於其他目的)。是的,我也嘗試過在我的AppController類中包含iostream,但它沒有解決任何問題(我也沒有真正期望它)。

所以我不確定問題是什麼。有任何想法嗎?

回答

30

字符串位於標準名稱空間中。

#include <string> 
... 
std::string myString; 

或者您可以使用

using namespace std; 

然而,這是一個非常糟糕的事情在頭做,因爲它會污染任何人都全局命名空間的,包括所述頭。儘管對於源文件來說沒關係。還有一個額外的語法,你可以使用(即具有一些相同的問題,使用的命名空間一樣):

using std::string; 

這也將帶來字符串類型名稱到全局命名空間(或當前命名空間),並作爲這通常應該在標題中避免。

+1

+1用於避免在標題 – 2011-02-04 02:10:02