【问题标题】:Why am I getting string does not name a type Error?为什么我得到字符串没有命名类型错误?
【发布时间】:2011-07-28 12:18:19
【问题描述】:

游戏.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

【问题讨论】:

    标签: c++ string std


    【解决方案1】:

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

    作为others have pointed out,这是标题中的not good practice——包含该标题的每个人也会不自觉地点击using行并将std导入他们的命名空间;正确的解决方案是将这些行改为使用std::string

    【讨论】:

    • @Michael Mrozek, @Steven:将using namespace std; 移动到标题中是一种卑鄙的行为。建议它加倍!
    • @Johnsyweb 我个人完全讨厌using namespace,但这显然是他的意图
    • @Michael:更有理由劝阻他!
    • @Johnsyweb 我讨厌在互联网上搜索问题,看到有人问过同样的问题,而所有的答案都是“不,不要那样做”——我回答的问题是被问。我应该提到这是一个坏主意,是的,但我拒绝只说“不,这是不可能的”
    • @Michael:感谢您的编辑。我讨厌在网上搜索问题的解决方案,却发现最热门的是黑客攻击。 +1 :-)
    【解决方案2】:

    string 没有命名类型。 string 标头中的类称为std::string

    不要using namespace std 放在头文件中,它会污染该头文件的所有用户的全局命名空间。另见"Why is 'using namespace std;' considered a bad practice in 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);
    };
    

    【讨论】:

    • @Jonhsyweb: +1 指出using namespace 的危险
    • 除了包含在主.cpp文件中之外,#include 是否也应该包含在头文件中?
    • @Gnuey:由于任何编译单元(包括此标头)都需要 #include &lt;string&gt;,因此我会包括该行,是的。无需在任何后续源文件中重复此指令。
    【解决方案3】:

    只需在头文件中的 string 前面使用 std:: 限定符即可。

    事实上,您也应该将它用于istreamostream - 然后您需要在头文件的顶部使用#include &lt;iostream&gt; 以使其更加独立。

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

        您可以通过两种简单的方式克服此错误

        第一种方式

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-06
          • 1970-01-01
          • 2013-08-17
          相关资源
          最近更新 更多