在C++中组合时,重载运算符"="和"+"不起作用

Mr *_*old 2 c++ overloading class operator-overloading

#include <iostream>
using namespace std;
class A
{
public:
    A(int a)
    {
        length = a;
    }
    ~A(){}

    friend A operator +(A& var1, A& var2);
    A& operator=(A &other);

    int length;
};

A operator +(A& var1, A& var2)
{
    return A(var1.length + var2.length);
}

A& A::operator=(A &other)
{
    length = other.length;
    return *this;
}


int main()
{
    A a(1);
    A b(2);
    A c(3);
    c = a;   // work
    c = a + b;  // does not work
    cout << c.length ;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在main()中,c = a成功编译但"c = a + b"不成功.但是,在A&A :: operator =(A&other)中,如果我将(A&other)更改为(A other),那么它可以工作.这个案子可以帮到我吗?

Bil*_*nch 8

最简单的解决方法是让你的赋值重载通过const引用获取它的参数.

然后返回的临时a + b值可以与它一起使用.

A& A::operator=(A const & other)
{
    length = other.length;
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

您可能希望与您做同样的事情,operator+这样也c = a + a + a;可以.