【发布时间】:2017-07-28 15:37:03
【问题描述】:
所以我在名为 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。 “复制”:未知的覆盖说明符 缺少类型说明符 - 假定为 int。
我尝试将#include <string> 添加到头文件中并重新编译它,但它完全没有做任何事情。这让我感到困惑,因为我认为我可以使用字符串作为数据类型,但显然不在类中?如果有人可以帮助我,那就太好了,因为我不知道为什么我的代码不起作用。
【问题讨论】:
-
去掉
using namespace std,用std::string替换string,你的问题(包括你没有意识到的问题)就会消失。 -
using namespace std;在#include "Classes.h"之后。因此,在定义class PalindromCheck时,编译器会尝试在全局命名空间中找到string,但找不到。 (还没有。)答案中提供了解决方案...