为什么C++不允许我在类中使用字符串作为数据成员?

Why won't C++ let me use a string as a data member in a class?

本文关键字:字符串 数据成员 不允许 C++ 允许我 为什么      更新时间:2023-10-16

所以我在一个名为 Classes.h 的头文件中有以下代码:

#ifndef CLASSESS_H
#define CLASSESS_H
class PalindromeCheck
{
private:
string strToCheck;
string copy;
public:
PalindromeCheck(string testSubject) : strToCheck(testSubject) {} //Constructor
void Check()
{
copy = strToCheck; //Copy strToCheck into copy so that once strToCheck has been reversed, it has something to be checked against.
reverse(strToCheck.begin(), strToCheck.end());  //Reverse the string so that it can be checked to see if it is a palindrome.
if (strToCheck == copy) 
{
cout << "The string is a palindrome" << endl;
return;
}
else 
{
cout << "The string is not a palindrome" << endl;
return;
}
}
};
#endif

现在我在源文件中有以下代码:

#include <iostream>
#include <string>
#include <algorithm>
#include "Classes.h"
using namespace std;
int main()
{
PalindromeCheck firstCheck("ATOYOTA");
firstCheck.Check();
return 0;
}

当我使用 Visual C++ 编译器编译此代码时,我收到了大量错误消息,这些错误消息都源于前四条:

"strToCheck":未知的覆盖说明符 缺少类型说明符 - 假定为 int。 "copy":未知覆盖说明符 缺少类型说明符 - 假定为 int。

我尝试将#include <string>添加到头文件中并重新编译它,但它完全没有做任何事情。 这让我感到困惑,因为我认为我可以使用字符串作为数据类型,但显然不在类中? 如果有人可以帮助我,那就太好了,因为我不知道为什么我的代码不起作用。

您需要在类标头本身中#include <string>

您还需要使用std::命名空间(最好(或者也向该标头添加using namespace std(我强烈建议不要这样做(。

相关文章: