C++基础:为什么不能cout一个string

如题所述

综上,cout函数重载的是string类库中的string类型,而不是CString或string.h中的。

例:

#include<iostream>
#include<CString>
//#include<string.h>
 
using std::cout;
using std::string ;
using std::endl;
 
main()
{
string a;
a="*******";
cout<<a<<endl;
 
}
当编译这个程序时,会出现这样的如上的error,而如果把上面的头文件改为#include<string>时,error就会消失。
 
而在MFC中或你包含的是CString头文件,如果想用cout输出string 类型,则需要先把string类型转换char*型,如上面例子:
#include<iostream>
#include<CString>
 
using std::cout;
using std::string ;
using std::endl;
 
main()
{
string a;
a="*******";
   char* b=(char*)a.c_str(); //将string类型转为char*
cout<<b<<endl;
}

温馨提示:答案为网友推荐,仅供参考