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

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

我收到错误:标识符“字符串”未定义。

但是,我将 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();
};

有人可以向我解释一下为什么会发生这种情况吗?

c++ string
8个回答
132
投票

<string.h>
是旧的 C 标头。 C++提供了
<string>
,那么应该简称为
std::string


29
投票

您想要执行

#include <string>
而不是
string.h
,然后类型
string
位于
std
命名空间中,因此您需要使用
std::string
来引用它。


14
投票

您忘记了您所指的名称空间。添加

using namespace std;

始终避免使用 std::string 。


11
投票

因为

string
是在命名空间
std
中定义的。将
string
替换为
std::string
,或添加

using std::string;

在您的

include
线下方。

它可能适用于

main.cpp
,因为其他一些标头中有此
using
行(或类似的内容)。


7
投票

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

指定命名空间

5
投票

也许您想要

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


5
投票

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

using namespace std;

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

std::string level;

0
投票
std::string name = "akash";
© www.soinside.com 2019 - 2024. All rights reserved.