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

Ste*_*ven 64 c++ string std

game.cpp

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

using namespace std;
Run Code Online (Sandbox Code Playgroud)

game.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
Run Code Online (Sandbox Code Playgroud)

错误是:

game.h:8 error: 'string' does not name a type
game.h:9 error: 'string' does not name a type

Mic*_*zek 94

您的using声明在game.cpp,而不是game.h您实际声明字符串变量的位置.您打算在using namespace std;使用的行上方放入标题,string这将使这些行找到命名空间中string定义的类型std.

正如其他人所指出的那样,这不是标题中的好习惯 - 包含该标题的每个人也会不由自主地命中using并导入std其命名空间; 正确的解决办法是改变那些线使用std::string,而不是

  • @Johnsyweb我讨厌当我在互联网上搜索问题时,看到有人问过同样的问题,并且所有答案都是"不,不要那样做" - 我回答了被问到的问题.我应该提到这是一个坏主意,是的,但我拒绝只说"不,这是不可能的" (11认同)
  • @Michael Mrozek,@ Steve:将`使用命名空间std;`移动到标题中是一种卑鄙的行为.建议加倍 - 所以! (7认同)
  • @Michael:更有理由劝阻他! (3认同)
  • @Johnsyweb 我个人完全讨厌“使用命名空间”,但这显然是他打算做的 (2认同)
  • @Michael:谢谢你的编辑.我讨厌在网上搜索问题的解决方案,但却发现最受欢迎的是黑客攻击.+1 :-) (2认同)

Joh*_*web 37

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);
};
Run Code Online (Sandbox Code Playgroud)

  • @Jonhsyweb:+1 指出“使用命名空间”的危险 (2认同)

qua*_*ana 7

只需在头文件中使用std::限定符即可string.

事实上,你应该使用它,istream并且ostream- 然后你需要#include <iostream>在头文件的顶部使它更自包含.


Bor*_*lid 5

尝试using namespace std;在顶部game.h或使用完全限定std::string而不是string.

namespacegame.cpp是被包括在报头之后.