C++ 标识符“字符串”未定义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7146719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
identifier "string" undefined?
提问by Rhexis
I am receiving the error: identifier "string" undefined.
我收到错误:标识符“字符串”未定义。
However, I am including string.h and in my main file, everything is working fine.
但是,我包含 string.h 并且在我的主文件中,一切正常。
CODE:
代码:
#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();
};
Can someone please explain to me why this is occurring?
有人可以向我解释为什么会发生这种情况吗?
回答by Puppy
<string.h>is the old C header. C++ provides <string>, and then it should be referred to as std::string.
<string.h>是旧的 C 头文件。C++ 提供了<string>,那么它应该被称为std::string.
回答by Flexo
You want to do #include <string>instead of string.hand then the type stringlives in the stdnamespace, so you will need to use std::stringto refer to it.
你想要做#include <string>而不是string.h然后类型string存在于std命名空间中,所以你需要使用std::string来引用它。
回答by Ernest Friedman-Hill
Because stringis defined in the namespace std. Replace stringwith std::string, or add
因为string是在命名空间中定义的std。替换string为std::string,或添加
using std::string;
below your includelines.
在你的include线下。
It probably works in main.cppbecause some other header has this usingline in it (or something similar).
它可能有效,main.cpp因为其他一些标题中有这一using行(或类似的东西)。
回答by Nicol Bolas
Perhaps you wanted to #include<string>, not <string.h>. std::stringalso needs a namespace qualification, or an explicit usingdirective.
也许你想#include<string>,不是<string.h>。std::string还需要命名空间限定或显式using指令。
回答by m0skit0
You forgot the namespace you're referring to. Add
你忘记了你所指的命名空间。添加
using namespace std;
using namespace std;
to avoid std::string all the time.
一直避免 std::string 。
回答by Camelot
You must use std namespace. If this code in main.cpp you should write
您必须使用 std 命名空间。如果这个代码在 main.cpp 你应该写
using namespace std;
If this declaration is in header, then you shouldn't include namespace and just write
如果这个声明在标题中,那么你不应该包含命名空间而只写
std::string level;
回答by Pierre Lacave
#include <string>would be the correct c++ include, also you need to specify the namespace with std::stringor more generally with using namespace std;
#include <string>将是正确的 c++ 包含,您还需要指定命名空间 withstd::string或更一般地using namespace std;

