为什么在 #include 之后仍然需要使用 std::string<string>?
Why is using std::string still needed after #include <string>?
要使用字符串,我需要包括字符串标题,以便其实现可用。但是,如果是这样,为什么我仍然需要添加行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
是标准名称空间。 cout
, cin
, string
和许多其他内容都定义了。
标题<string>
声明与字符串库有关的各种实体,而名称空间用于分组相关功能并允许在不同的名称空间中使用相同名称。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- std::string, std::wstring and UTF8
- uan inplace replacement of std::string/std::wstring?
- #define Glib::string std:wstring
- 从 std::string & std::wstring 中获取 char 整数值
- BSTR转换为std::string(std::wstring),反之亦然