c++ - 重载赋值和加运算符

标签 c++ operator-overloading

#include<iostream>
using namespace std;

class test
{
    int i;
    string s;

    public:
    test(){}

    test(int a,string b)
    {
        i=a;
        s=b;
    }

    void operator = (test &temp)
    {
        cout<<"In assignment operator"<<endl;
        i=temp.i;
        s=temp.s;
    }

    test  operator + (test &temp)
    {
        test newobj;
        newobj.i=i+temp.i;
        newobj.s=s+" "+temp.s;
        return newobj;
    }
};

main()
{
    test t1(5,"ABC");
    test t2;
    t2=t1;
    test t3;
    t3=t1+t2;
}

问题:t3=t1+t2 给我一个错误。我想重载 = 和 + 运算符并如上所示使用它们。我哪里错了?我想显式定义一个赋值运算符重载,即使编译器提供了一个。

error : invalid initialization of non-const reference of type ‘test&’ from an rvalue of type ‘testt3=t1+t2;

initializing argument 1 of ‘void test::operator=(test&)void operator = (test &temp)

最佳答案

t1+t2 返回一个临时的 test,它不能绑定(bind)到对非常量的引用(即 test &),这就是 t3=t1+t2; 失败的原因。另一方面,temporary 可以绑定(bind)到对 const 的引用(即 const test&)。所以你可以把参数类型改成const test&,例如

void operator = (const test &temp)
{
    cout<<"In assignment operator"<<endl;
    i=temp.i;
    s=temp.s;
}

顺便说一句:最好用 operator+ 做同样的事情。

BTW2:operator= 的常规签名(和实现)是:

test& operator= (const test& temp)
{
    cout<<"In assignment operator"<<endl;
    i = temp.i;
    s = temp.s;
    return *this;
}

关于c++ - 重载赋值和加运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44300010/

相关文章:

c++ - OpenGL 和 GLSL : Greyscale texture not showing

c++ - 这是查找动态分配数组长度的好方法吗?

C++:使用 std::unique_ptr 访问重载 operator++ 的最佳方式?

C++ - << 运算符重载,链表 - 地址而不是标准输出

c++ - 当您可以使用构造函数时,为什么要在 C++ 类或结构中重载 () 运算符(可调用运算符)?

c++ - 无法使用复印功能

c++ - 从继承中解决循环依赖

c++ - 重载运算符函数失败

c++ - 这些 C++ 运算符重载有什么问题?

c++ - 这 std::ref 行为合乎逻辑吗?