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

Why is using std::string still needed after #include <string>?

为了使用字符串,我需要包含字符串 header,以便它的实现可用。但如果是这样,为什么我还需要添加行 using std::string?

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

#include <string>

using std::string;

int main() {
    string s1;
}

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

你可以在包含 <string> 的任何地方写 std::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
}

Namespace是C++的一个附加特性,它定义了变量、函数或object的作用域,避免了名称冲突。这里,string object 定义在 std 命名空间中。

std 是标准命名空间。 coutcinstring 和很多其他的东西都在里面定义了。

header <string> 声明了与字符串库相关的各种实体,而命名空间用于对相关功能进行分组,并允许在不同的命名空间中使用相同的名称。

因为classstring的声明在命名空间std中。因此,您要么需要始终通过 std::string 访问它(然后您就不需要使用),要么像以前那样访问它。

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

下面的代码是正确的:

#include <string>

int main()
{
    std::string s1;
    return 0;
}