为什么我得到字符串没有命名类型错误
Why am I getting string does not name a type Error?
game.cpp
#include <iostream>
#include <string>
#include <sstream>
#include "game.h"
#include "board.h"
#include "piece.h"
using namespace std;
游戏.h
#ifndef GAME_H
#define GAME_H
#include <string>
class Game
{
private:
string white;
string black;
string title;
public:
Game(istream&, ostream&);
void display(colour, short);
};
#endif
错误是:
game.h:8 error: 'string' does not name a type
game.h:9 error: 'string' does not name a type
您的using
声明在game.cpp
中,而不是game.h
实际声明字符串变量的位置。您打算将using namespace std;
放入标头中,位于使用 string
的行上方,这将使这些行找到在 std
命名空间中定义的string
类型。
正如其他人所指出的,这在标头中不是好的做法 - 每个包含该标头的人也会不由自主地点击using
行并将std
导入到他们的命名空间中;正确的解决方案是更改这些行以使用std::string
string
不命名类型。string
标头中的类称为 std::string
。
请不要将using namespace std
放在头文件中,它会污染该头文件的所有用户的全局命名空间。另请参阅"为什么'使用命名空间 std;'在C++中被认为是一种不好的做法?
您的类应如下所示:
#include <string>
class Game
{
private:
std::string white;
std::string black;
std::string title;
public:
Game(std::istream&, std::ostream&);
void display(colour, short);
};
只需在头文件中string
前面使用 std::
限定符即可。
事实上,你也应该用它来istream
和ostream
- 然后你需要在头文件的顶部#include <iostream>
,以使其更加独立。
尝试在
game.h
顶部使用using namespace std;
或使用完全限定的std::string
而不是string
。
game.cpp
中的namespace
是在包含标头之后。
您可以通过两种简单的方式克服此错误
第一种方式
using namespace std;
include <string>
// then you can use string class the normal way
第二种方式
// after including the class string in your cpp file as follows
include <string>
/*Now when you are using a string class you have to put **std::** before you write
string as follows*/
std::string name; // a string declaration
相关文章:
- 类没有命名C++代码中的类型错误
- 不完整类型错误(E0409、E0070、E0515)
- 使用具有结构不完整类型错误的模板
- 不命名构造函数和析构函数上的类型错误
- 返回派生类型时出现协变类型错误
- 为什么此构造函数没有给出不完整的类型错误?
- 定义模板化结构的特征时出现不完整的类型错误
- 使用重载构造函数时出现不完整的类型错误
- 为什么我得到表达式必须有类类型错误?
- 输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误
- 枚举成员不是类型错误
- 如何修复"ctypes"。参数错误:参数 2:<键入"异常.类型错误">:RaspberryPi 中的错误类型"错误
- 外部 "C" Visual Studio 2015 中的显式类型错误,DLL 测试代码
- 非默认析构函数会导致不完整的类型错误
- 为什么按引用传入会导致绑定引用类型错误
- Objective-C C++ 包装器 类型错误的不完整定义
- 输入类型错误
- 当构造函数的参数类型错误时引发异常
- 命名空间中的'bad_cast' 'std' 未命名类型错误
- C UNWORKOWN类型错误