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

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

本文关键字:string std lt gt 之后 #include 为什么      更新时间:2023-10-16

要使用字符串,我需要包括字符串标题,以便其实现可用。但是,如果是这样,为什么我仍然需要添加行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
}

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

以下代码是正确的:

#include <string>
int main()
{
    std::string s1;
    return 0;
}

,因为string类声明在命名空间std中。因此,您要么需要始终通过std :: string(然后您不需要使用)或像这样做。

Namespace是C 的另一个功能,它定义了变量,函数或对象的范围,并避免了名称collision。在这里,string对象定义在std名称空间中。

std是标准名称空间。 coutcinstring和许多其他内容都定义了。

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