我是C++新手。我最近正在制作一个使用单独文件中的类的小程序。我也想使用setter和getter(设置& get)函数为变量赋值。编译器给我一个奇怪的错误,当我运行该程序。它说'字符串'不会命名一个类型。下面是代码:'字符串'不会命名一个类型 - C++错误
MyClass.h
#ifndef MYCLASS_H // #ifndef means if not defined
#define MYCLASS_H // then define it
#include <string>
class MyClass
{
public:
// this is the constructor function prototype
MyClass();
void setModuleName(string &);
string getModuleName();
private:
string moduleName;
};
#endif
MyClass.cpp文件
#include "MyClass.h"
#include <iostream>
#include <string>
using namespace std;
MyClass::MyClass()
{
cout << "This line will print automatically because it is a constructor." << endl;
}
void MyClass::setModuleName(string &name) {
moduleName= name;
}
string MyClass::getModuleName() {
return moduleName;
}
的main.cpp文件
#include "MyClass.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
MyClass obj; // obj is the object of the class MyClass
obj.setModuleName("Module Name is C++");
cout << obj.getModuleName();
return 0;
}
'std :: string moduleName;' – SergeyA
我没有得到它。我应该修改哪个文件?你可以一步一步解释。 –
我和很多其他人强烈建议不要试图通过在标题中添加'using namespace std ;'来解决此问题。它并不总是会导致痛苦,但它会导致比您想要忍受的更多的悲伤。更多在这里:http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice – user4581301