标识符“字符串”未定义?

我收到错误: 标识符“ 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();
};

有人能解释一下为什么会这样吗?

182422 次浏览

因为 string是在名称空间 std中定义的

using std::string;

低于你的 include线。

它可能在 main.cpp中工作,因为其他头中有这样的 using行(或类似的内容)。

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

您希望执行 #include <string>而不是 string.h,然后类型 string存在于 std名称空间中,因此需要使用 std::string来引用它。

也许您想要的是 #include<string>,而不是 <string.h>.std::string还需要一个名称空间限定,或者一个显式的 using指令。

您忘记了所引用的名称空间

using namespace std;

避免一直使用 std: : string。

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

必须使用 std 名称空间

using namespace std;

如果这个声明在 header 中,那么不应该包含名称空间,而应该只写

std::string level;