为什么我得到字符串不命名类型错误?

Game.cpp

#include <iostream>
#include <string>
#include <sstream>
#include "game.h"
#include "board.h"
#include "piece.h"


using namespace std;

游戏

#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

303911 次浏览

尝试在 game.h的顶部使用 using namespace std;或者使用完全合格的 std::string而不是 string

game.cpp中的 namespace在包含头部之后。

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::限定符即可。

事实上,您也应该将它用于 istreamostream-然后您将需要在头文件的顶部使用 #include <iostream>来使其更加自包含。

您可以通过两种简单的方法来克服这个错误

第一条路

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