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

Hay*_*den -2 c++ string stl class

所以我在名为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
Run Code Online (Sandbox Code Playgroud)

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

#include <iostream>
#include <string>
#include <algorithm>
#include "Classes.h"
using namespace std;

int main()
{
    PalindromeCheck firstCheck("ATOYOTA");

    firstCheck.Check();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Cor*_*mer 7

你需要#include <string>在类头文件中.

您还需要使用std::命名空间(最好)或者也添加using namespace std到该标题(我强烈反对).