【发布时间】:2016-04-14 17:03:44
【问题描述】:
我是 C++ 新手。我最近正在制作一个使用单独文件中的类的小程序。我还想使用 setter 和 getter (set & get) 函数为变量赋值。当我运行程序时,编译器给了我一个奇怪的错误。它说“字符串”没有命名类型。代码如下:
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; -
我没听懂。我应该修改哪个文件?你能逐步解释一下吗?
-
我和许多其他人强烈建议不要尝试通过在标题中添加
using namespace std;来解决此问题。它并不总是会导致痛苦,但它会导致比你想忍受的更多的悲伤。更多信息:stackoverflow.com/questions/1452721/… -
SergeyA 的观点是没有
string这样的东西。但是有std::string。您正在使用 wring 名称。 -
@downvoters 找一个好的骗子或者闭嘴。
标签: c++ c++11 compiler-errors