为什么在#include< string>之后仍然需要使用std :: string? [英] Why is using std::string still needed after #include <string>?
问题描述
为了使用字符串,我需要包含字符串标题,以便它的实现可用。但如果是这样,为什么我仍然需要使用std :: string 添加行?
In order to use strings I need to include the string header, so that its implementation becomes available. But if that is so, why do I still need to add the line using std::string
?
为什么它是否已经知道字符串数据类型?
Why doesn't it already know about the string data type?
#include <string>
using std::string;
int main() {
string s1;
}
推荐答案
因为 string
在命名空间中定义,名为 std
。
Because string
is defined within namespace called std
.
你可以写 std :: string
包含< string>
的地方,但你可以使用std :: string添加
并且不在范围内使用命名空间(因此 std :: string
可能被称为 string
)。您可以将它放置在函数内部,然后它仅适用于该函数:
you can write std::string
everywhere where <string>
is included but you can add using std::string
and don't use namespace in the scope (so std::string
might be reffered to as string
). You can place it for example inside the function and then it applies only to that function:
#include <string>
void foo() {
using std::string;
string a; //OK
}
void bar() {
std::string b; //OK
string c; //ERROR: identifier "string" is undefined
}
这篇关于为什么在#include< string>之后仍然需要使用std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!