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

Why am I getting string does not name a type Error?

本文关键字:类型 错误 字符串 为什么      更新时间:2023-10-16

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

事实上,你也应该用它来istreamostream - 然后你需要在头文件的顶部#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