[英]Operator Overloading working but giving stack overflow and crashing in C++
[英]Stack overflow when overloading << operator
#include<iostream>
using namespace std;
class aClass
{
public:
char *message;
aClass(const char *message);
~aClass(){delete[] message;}
};
aClass::aClass(const char* newmessage)
{
message = new char[strlen(newmessage) +1];
strcpy(message,newmessage);
}
const ostream& operator<<(const ostream& o, const aClass &a)
{
o << a.message;
return o;
}
int main()
{
aClass b("Hello");
cout << b;
}
有人可以向我解釋為什么上面的代碼會產生無限循環嗎?
因為你有const
不應該是:
///// /////
const ostream& operator<<(const ostream& o, const aClass &a)
輸出流假設是非const的; 畢竟,輸出數據正在發生變化。 所以當你這樣做時:
o << a.message;
它不能使用char*
的正常重載,因為它可以在非const流上運行。 相反,它搜索適當的過載,發現你的,決定了它可以構造一個aClass
從a.message
(因為你的構造不explicit
),這樣做,並調用它。 這永遠重復。
它應該寫成:
ostream& operator<<(ostream& o, const aClass &a)
{
o << a.message;
return o;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.