简体   繁体   English

重载<<运算符时堆栈溢出

[英]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;
}

Can someone explain to me why the code above produces an infinite loop? 有人可以向我解释为什么上面的代码会产生无限循环吗?

Because you have const where it shouldn't be: 因为你有const不应该是:

/////                     /////
const ostream& operator<<(const ostream& o, const aClass &a)

The output stream is suppose to be non-const; 输出流假设是非const的; after all, outputting data is changing something. 毕竟,输出数据正在发生变化。 So when you do this: 所以当你这样做时:

o << a.message;

It cannot use the normal overload for char* , because that one operates on a non-const stream. 它不能使用char*的正常重载,因为它可以在非const流上运行。 Instead, it searches for an appropriate overload and finds yours, determines it can construct an aClass from a.message (because your constructor is not explicit ), does so, and calls it. 相反,它搜索适当的过载,发现你的,决定了它可以构造一个aClassa.message (因为你的构造不explicit ),这样做,并调用它。 This repeats forever. 这永远重复。

It should be written as: 它应该写成:

ostream& operator<<(ostream& o, const aClass &a)
{
    o << a.message;
    return o;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM