代码如下:
#include
#include
using namespace std;
class String{
char* array;
public:
String(const char* p){
array=new char[strlen(p)+1];
strcpy(array,p);
}
~String(){ delete[] array; }
String operator+(const char* b) {
char* p=new char[strlen(array)+strlen(b)+1];
strcpy(p,array);
strcat(p,b);
return String(p);
}
operator int(){
return strlen(array);
}
friend ostream& operator<<(ostream& output, String& a)
{
output<<a.array;
return output;
}
};
int main()
{
String string1("mystring");
cout<<string1+"ab"<<endl;
cout<<string1<<endl;
cout<<string1+3<<endl;
cout<<string1<<endl;
return 0;
}
运行结果为:
10
mystring
11
mystring
问题:重载执行了string1+"ab",返回临时对象,用cout输出时竟然又将临时对象转为int,而没有调用<<重载。但如果<<重载第二参数前加const,则输出为:
mystringab
mystring
11
mystring
谁能解释一下?

重载输出运算符时的怪问题
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- encryptotion 2022-05-16 23:25关注
对于main函数第二句cout<<string1+"ab",先执行+重载返回临时对象,然后编译器试图匹配<<运算符的重载。因为自动生成的临时对象都是const的,而const对象是无法转换成非const对象。所以与<<重载函数第二参数不能匹配,因而编译器尝试进行类型转换。
编译器匹配次序是先找能运算符重载函数,如果不能匹配,才尝试类型转换函数。本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录