简单的用户定义 class with operator = 重载代码崩溃

simple user defined class with operator = overloading code crashed

我正在测试一个简单的运算符重载代码,在测试时,这段代码在 "nd.print()" 处崩溃(核心转储)。有什么建议吗?

崩溃发生在 ubuntu 16.04 64 位。我在网上试了一些shell的环境,比如https://www.onlinegdb.com/online_c++_compiler,好像还可以。

#include <iostream>
using namespace std;

class Node
{
    int d;
    public:
    Node (int dd = 0):d(dd){}
    Node &operator=(Node &nd){ d = nd.d; }
    void print(){ cout<<d<<endl; }
};

int main()
{
    Node nd1(1), nd2(2);
    Node nd;
    nd = nd2 = nd1;
    nd.print();    //*******Crash here
    return 0;
}

我希望它只打印一个值而不会崩溃。

operator=方法需要return分配的变量。事实上,它没有 returning 任何东西(尽管签名说你会 - 你可能有一个关于它的编译器警告),所以 nd = ... 位正在分配一个未定义的值。然后您尝试对该未定义的值调用 print 方法。

在这种情况下,您想要return分配的值,即*this:

Node &operator=(Node &nd)
{
    d = nd.d;
    return *this;
}