今天在visual studio 学习c++的string类,发现string的不能用c++的cout函数来输出,后来查了下网上的资料发现应该是能够的,最后才发现本身没有进行导入c++的默认的string的头文件,因此它默认的使用cout不能够使用,编译时出现这样一个错误:linux
error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is ios
no acceptable conversion)c++
答案:首先得说这个问题的答案是确定的,cout重载了string类型,因此在c++ 中能够直接输出。数组
先来看CString、string和string.h这几个区别:函数
CSting:CString是MFC或者ATL中的实现,是MFC里面封装的一个关于字符串处理的功能很强大的类,只有支持MFC的工程才能够使用。如在linux上的工程就不能用CString了,只能用标准C++中的string类了。在MFC中使用不须要本身加,但在另外的程序中须要加入#include<CString>。学习
string:string类既是一个标准c++的类库,同时也是STL(Standard Template Library,标准模版库)中的类库,已经归入C++标准之中。它和CString有本质的区别。spa
string.h:C语言里面关于字符数组的函数定义的头文件,经常使用函数有strlen、strcmp、strcpy等等,这个头文件跟C++的string类半点关系也没有,因此 <string>并不是 <string.h>的“升级版本”,他们是毫无关系的两个头文件。htm
综上,cout函数重载的是string类库中的string类型,而不是CString或string.h中的。字符串
例:get
1 #include<iostream> 2 #include<CString> 3 //#include<string.h> 4 5 using std::cout; 6 using std::string ; 7 using std::endl; 8 9 main() 10 { 11 string a; 13 a="*******"; 15 cout<<a<<endl; 16 }
当编译这个程序时,会出现这样的如上的error,而若是把上面的头文件改成#include<string>时,error就会消失。
而在MFC中或你包含的是CString头文件,若是想用cout输出string 类型,则须要先把string类型转换char*型,如上面例子:
1 #include<iostream> 2 #include<CString> 3 4 using std::cout; 5 using std::string ; 6 using std::endl; 7 8 main() 9 { 10 string a; 11 a="*******"; 12 char* b=(char*)a.c_str(); //将string类型转为char* 13 cout<<b<<endl; 14
总结:参考了网上的一些资料之后,其实就是使用对 你想用的函数方法、类的时候,须要对号入座,以为这样避免一些比较低级的问题。