为什么我收到 string does not name a type 错误?

问题描述 投票:0回答:5

游戏.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
5个回答
114
投票

您的

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

正如其他人指出的那样,这在标头中是“不好的做法”——每个包含该标头的人也会不自觉地点击using行并将

std
导入到他们的命名空间中;正确的解决方案是更改这些行以使用
std::string
代替
    


50
投票
string

不命名类型。

string
标头中的类称为
std::string

不要

using namespace std放入头文件中,它会污染该头文件的所有用户的全局命名空间。另请参阅

“为什么是‘using namespace 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); };



10
投票
std::

前面使用

string
限定符即可。

事实上,您还应该将它用于

istream

ostream
- 然后您将需要在头文件顶部使用
#include <iostream>
以使其更加独立。
    


5
投票
using namespace std;

顶部添加

game.h
或使用完全限定的
std::string
代替
string

namespace

中的

game.cpp
位于包含标题之后。
    


4
投票
您可以通过两种简单的方法克服此错误

第一种方法

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

© www.soinside.com 2019 - 2024. All rights reserved.