简体   繁体   中英

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 ostream& operator<<(const ostream& o, const aClass &a)

The output stream is suppose to be non-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. 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. This repeats forever.

It should be written as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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