C++ 为什么cout需要标题字符串?
为什么在下面的代码中不包含“string”头我可以声明string变量。 但当我试图打印字符串时,编译器只会抱怨cout “字符串”标题包含哪些信息C++ 为什么cout需要标题字符串?,c++,string,C++,String,为什么在下面的代码中不包含“string”头我可以声明string变量。 但当我试图打印字符串时,编译器只会抱怨cout “字符串”标题包含哪些信息 #include <iostream> //#include "string" int main () { std::string str="SomeWorld"; std::cout<<str<<std::endl; return 0; } #包括 //#包括“字符串” int
#include <iostream>
//#include "string"
int main ()
{
std::string str="SomeWorld";
std::cout<<str<<std::endl;
return 0;
}
#包括
//#包括“字符串”
int main()
{
std::string str=“SomeWorld”;
std::cout它不是std::cout
所必需的,它是std::string
所必需的,因为定义std::basic_string
的头很可能(间接地)包含在
中(std::string
是基于std::basic_string
的类型定义).操作符的
头的重载包括字符串类的定义(注意:#include“string”
意味着将字符串
文件包含在当前目录中,因此对于系统包含,您应该使用尖括号而不是”
)
但是,iostream
已经包括string
,(例如,声明运算符,因为
包含在
中。这就是编译器没有抱怨的原因。严格地说,除非包含所有正确的头,否则任何事情都可能发生。没有强制要求将一个标准头包含在任何其他头中。因此,为了便于移植和正确,您必须y这是:
#include <string> // for `std::string`
#include <ostream> // for `std::ostream &` in `operator<<`
#include <iostream> // for std::cout
int main() {
std::string str = "hello world";
std::cout << str << std::endl;
}
#include//for`std::string`
#include//for`std::ostream&`在`operatorIn Visual C++的情况下,
包括实现定义的
头,该头定义了基本字符串本身,但正如您所说,它不定义运算符++。不包括“字符串”"标头I可以声明STD::String变量。编译器允许这样做。@用户-允许一个C++头包含任何其他的头。但是,您不能依赖这个,因为它从一个编译器到另一个。您需要总是包括您需要的头。@ USER430244:您总是需要一个包含类型的头文件。。其他一切都是实现的东西,而不是你可以依赖的东西。@Bo:注意,在这种情况下,
没有包含另一个头,它包含了“半个头”——std::string
在那里,但是运算符提问者报告编译器确实抱怨过。我认为投票一次就足够了。