标识符"string"undefined?

Rhe*_*xis 43 c++ string

我收到错误:标识符"字符串"未定义.

但是,我包括string.h,在我的主文件中,一切正常.

码:

#pragma once
#include <iostream>
#include <time.h>
#include <string.h>

class difficulty
{
private:
    int lives;
    string level;
public:
    difficulty(void);
    ~difficulty(void);

    void setLives(int newLives);
    int getLives();

    void setLevel(string newLevel);
    string getLevel();
};
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释为什么会这样吗?

Pup*_*ppy 81

<string.h>是旧的C头.C++提供<string>,然后它应该被称为std::string.

  • 不要'使用命名空间std`,我已经低估了推荐这个原因的所有答案. (6认同)
  • 使用命名空间std (4认同)

Fle*_*exo 12

您想要#include <string>而不是string.h,然后类型字符串存在于std命名空间中,因此您需要使用string.h它来引用它.


m0s*_*it0 9

你忘记了你所指的命名空间。添加

using namespace std;

一直避免 std::string 。

  • 对于那些投反对票的人:感谢您的建设性意见:P (4认同)
  • `using namespace std;` 真的很糟糕,尤其是在标题中。 (2认同)
  • 谢谢!你能解释一下为什么吗? (2认同)
  • [这里](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-thinked-a-bad-practice-in-c)(如果有人想知道) (2认同)

Ern*_*ill 8

因为string在命名空间中定义std.更换stringstd::string,或加

using std::string;
Run Code Online (Sandbox Code Playgroud)

低于你的include线.

它可能适用,main.cpp因为其他一些标题中有这一using行(或类似的东西).


Pie*_*ave 6

#include <string>将是正确的 C++ 包含,您还需要指定命名空间std::string或更一般地使用using namespace std;


Nic*_*las 5

也许你想#include<string>,不是<string.h>std::string还需要命名空间限定或显式using指令。


小智 5

您必须使用 std 命名空间。如果这段代码在 main.cpp 中你应该写

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

如果此声明位于标头中,则不应包含名称空间而只需编写

std::string level;
Run Code Online (Sandbox Code Playgroud)