我目前正在用 C++ 为一个类定义一些属性,但是在使用类型 string
而不是 int
或 双
。例如:
private:
int LOT;
public:
int getLOT() {
return LOT;
}
void setLOT(int value) {
LOT = value;
}
工作正常,但是:
private:
string name;
public:
string getName() {
return name;
}
void setName(string value) {
name = value;
}
抛出这些错误:
https://s26.postimg.org/wm5y7922h/error.png
文件(标题)看起来像这样:
#include "general.h" // a header which includes all my other #includes
// which, yes, does include <string>
class MyClass
{
private:
string name;
public:
string getName() {
return name;
}
void setName(string value) {
name = value;
}
// other properties similar to the above
}
目的是像这样访问变量:
cout << "Enter your name: ";
cin >> MyClass.setName();
cout << "\nHello, " << MyClass.getName();
// although this isn't exactly how it'll be used in-program
如果有人可以就我做错的事情提供帮助或提供处理字符串属性的更好方法(就像我之前提到的那样,其他类型可以正常工作),我们将不胜感激。谢谢。
最佳答案
string
是 std
命名空间的一部分。
您必须使用 std::string
而不是 string
或添加 using namespace std;
(我不建议您在你的头文件,阅读 "using namespace" in c++ headers )。
关于c++ - 在 C++ 中对类属性使用字符串数据类型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46127002/