2014-03-04 46 views
0

main.cpp中:爲什麼我的簡單C++程序給我錯誤。

#include <iostream> 
#include "PrintText.h" 
#include <string> 

using namespace std; 

int main() 
{ 
PrintText tOb("Mwhahahaahhaha"); 
cout << tOb.getText() << endl; 
return 0; 
} 

PrintText.cpp:

#include "PrintText.h" 
#include <iostream> 
#include <string> 

using namespace std; 

PrintText::PrintText(string z){ 
setText(z); 
} 

void PrintText::setText(string x){ 
text = x; 
} 

string PrintText::getText(){ 
return text; 
} 

PrintText.h:

#ifndef PRINTTEXT_H 
#define PRINTTEXT_H 

class PrintText{ 
public: 
PrintText(string z); 
void setText(string x); 
string getText(); 
private: 
string text; 
}; 

#endif 

遇到錯誤說字符串尚未聲明和字符串做不是在我的.h文件中輸入一個類型,我不明白爲什麼。

+6

你必須'#include '而且它會是std :: string。 – pippin1289

+1

在頭文件中加入'#include '。 – CroCo

+0

@userX - 聽過縮進? –

回答

4
  • #include <string>在你的頭文件的聲明

  • 使用std::string而不是string

  • 之前,永遠不要放置using namespace聲明在頭文件

+0

感謝它現在正常工作。但如果你不介意回答他們,我還有另外幾個問題。 1.我如何知道何時使用std ::是否有一個數據類型列表等,以便我可以將它用於未來的程序。 2.爲什麼不能在.h文件中使用名稱空間。 – user3381220

+0

2)[why-is-using-namespace-std-considered-bad-practice](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) –

+0

@ user3381220標準庫的所有類型和功能(您可以包含「即插即用」的所有內容)位於'std'命名空間中。 2)'using namespace'基本上恢復命名空間,只有當你明確知道你在做什麼(比如強制轉換)時才使用它。但是,如果你把它放在一個標題中,你基本上會「強制」每個使用你的類/標題的人,而不能決定他們是否想要這樣做。 – Paranaix

2

修改頭文件如下

#ifndef PRINTTEXT_H 
#define PRINTTEXT_H 
#include <string> 

class PrintText{ 
public: 
    PrintText(std::string z); 
    void setText(std::string x); 
    std::string getText(); 
private: 
    std::string text; 
}; 

#endif 

而且您不需要在.cpp文件中再次包含#include <string>

相關問題