首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么C++不允许我在类中使用字符串作为数据成员?

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

Stack Overflow用户
提问于 2017-07-28 23:37:03
回答 1查看 1.5K关注 0票数 -2

因此,我在一个名为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;
}

当我使用可视化C++编译器编译这段代码时,我得到了大量的错误消息,它们都源于前四个错误:

“‘strToCheck”:未知的重写说明符缺少类型说明符-假定为int。“‘copy”:未知的重写说明符缺少类型说明符-假定为int。

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

EN

回答 1

Stack Overflow用户

发布于 2017-07-28 23:37:47

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

您还需要使用std::名称空间(首选),或者还需要将using namespace std添加到该标头(which I strongly discourage)。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45377422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档