为什么我的简单C ++程序会给我错误。

时间:2014-03-04 23:32:41

标签: c++

main.cpp中:

#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文件中命名类型,我不明白为什么。

2 个答案:

答案 0 :(得分:4)

  • 在声明

  • 之前将#include <string>放入头文件中
  • 使用std::string代替string

  • 永远不要在头文件中放置using namespace语句

答案 1 :(得分: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>