我正在尝试对运算符'+'执行二进制重载,但输出错误,我不明白为什么?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我正在尝试对运算符'+'执行二进制重载,但输出错误,我不明白为什么?相关的知识,希望对你有一定的参考价值。

我不明白为什么输出错误,我创建了一个名为'test'的类,该类具有2个整数,并尝试通过添加两个类'b1'和'b2'来重载运算符'+'。

#include<conio.h>
#include<iostream>
using namespace std;

class test

    int a,b;
public:
    test()
    
        a=0;
        b=0;
    
    test(int x , int y)
    
        a=x;
        b=y;
    
    test operator + (test t);
    void disp()
    
    std :: cout<<"a is ="<<a<<"\n b is = "<<b;

;
test test :: operator + (test t)

    test temp;
    temp.a=a+t.a;
    temp.b=b+t.b;

int main()

    test b1,b2,b3;
    b1=test(10,20);
    b2=test(30,40);
    b3 = b1+b2;
    b3.disp();

答案

您具有未定义的行为,因为operator+未返回temp。您需要执行以下操作:

以上是关于我正在尝试对运算符'+'执行二进制重载,但输出错误,我不明白为什么?的主要内容,如果未能解决你的问题,请参考以下文章