使用operator =重载代码崩溃的简单用户定义类

问题描述 投票:0回答:1

我正在测试一个简单的运算符重载代码,在测试它时,这段代码只是在“nd.print()”崩溃(core dumped)。有什么建议吗?

崩溃发生在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;
}

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

c++ overloading operator-keyword
1个回答
5
投票

operator=方法需要返回指定的变量。实际上,它没有返回任何东西(虽然签名说你会 - 你可能有编译器警告它),所以nd = ...位分配一个未定义的值。然后尝试在该未定义的值上调用print方法。

在这种情况下,您想要返回指定的值,即*this

Node &operator=(Node &nd)
{
    d = nd.d;
    return *this;
}
© www.soinside.com 2019 - 2024. All rights reserved.