C++ 报错:no operator defined which takes a right-hand operand of type 'class std::bas
参考:https://blog.csdn.net/wen_yang/article/details/72631380
1 错误提示
binary ‘<<’ : no operator defined which takes a right-hand operand of type ‘class std::basic_string<char,struct std::char_traits,class std::allocator >’ (or there is no acceptable
2 错误原因
string类没有重载“<<”操作符,用cout不能直接输出string类型
3 错误代码
#include<iostream>
int global_int;
std::string global_str;
int main()
{
int local_int;
std::string local_str;
std::cout<<global_int<<global_str<<std::endl;
std::cout<<local_int<<local_str<<std::endl;
return 0;
}
4 解决办法
1.使用c_str()函数,string.c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址; c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.
#include<iostream>
int global_int;
std::string global_str;
int main()
{
int local_int;
std::string local_str;
std::cout<<global_int<<global_str.c_str<<std::endl;
std::cout<<local_int<<local_str.c_str<<std::endl;
return 0;
}
2.添加头文件#include<string>
#include<iostream>
#include<string>
int global_int;
std::string global_str;
int main()
{
int local_int;
std::string local_str;
std::cout<<global_int<<global_str<<std::endl;
std::cout<<local_int<<local_str<<std::endl;
return 0;
}