为什么在#include <string>之后仍然需要使用std :: string?

van*_*cke 1 c++ string using include

为了使用字符串,我需要包含字符串头,以便它的实现可用.但如果是这样,为什么我仍然需要添加线using std::string

为什么它不知道字符串数据类型?

#include <string>

using std::string;

int main() {
    string s1;
}
Run Code Online (Sandbox Code Playgroud)

Cad*_*hon 7

using std::string;并不意味着您现在可以使用此类型,但您可以使用此类型,而无需在类型名称std::之前指定命名空间.

以下代码是正确的:

#include <string>

int main()
{
    std::string s1;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


mpi*_*tek 5

因为string在命名空间内定义了std.

你可以std::string在任何地方写入<string>包含但你可以using std::string在范围内添加和不使用命名空间(因此std::string可能会被称为string).您可以将它放置在函数内部,然后它仅适用于该函数:

#include <string>

void foo() {
    using std::string;

    string a; //OK
}

void bar() {
    std::string b; //OK
    string c; //ERROR: identifier "string" is undefined
}
Run Code Online (Sandbox Code Playgroud)

  • @vanmarcke它在std命名空间的字符串头中定义.看看我的答案结尾处的链接. (2认同)