超载运算符有什么问题?



我正在学习C++(如果精确的话,重载运算符)。我尝试过载操作员+通过这种方式:

Complex4d Complex4d::operator+(const Complex4d &rvalue)
{
    return Complex4d(a() + rvalue.a(), b());
}

其中,右值.a()和a(),右值.b()与b()是Complex2d的对象。在Complex2d中,I类重载运算符+也是,通过这种方式:

Complex2d Complex2d::operator +(Complex2d &rvalue)
{
    return Complex2d(a() + rvalue.a(), b() + rvalue.b());
} 

如果我写这个:

Complex4d Complex4d::operator+(const Complex4d &rvalue)
{
    Complex2d test = rvalue.a();
    return Complex4d(a() + test, b());
}

一切都好。我做错了什么?

问题是,您正试图将临时引用绑定到非常量引用,这是不允许的,也没有意义:

Complex2d Complex2d::operator +(Complex2d &rvalue)
                                ^^^^^^^^^^^
return Complex4d(a() + rvalue.a(), b());
                       ^^^^^^^^^^

要修复它,请使其采用const引用,临时性可以绑定到该引用。构造正确性也适用。如果你不修改它(你不应该修改),就把它变成const

Complex2d Complex2d::operator +(const Complex2d &rvalue)
                                ^^^^^

另一个参数(*this)也没有修改:

Complex2d Complex2d::operator +(const Complex2d &rvalue) const
                                ^^^^^                    ^^^^^                

此外,我建议让它们成为免费功能,并重用其他代码:

Complex2d operator+(const Complex2d &lhs, const Complex2d &rhs) {
    auto ret = lhs;
    ret += rhs;
    return ret; //see comments for implementation reasoning
}

这允许左侧的行为与右侧相同,并通过访问类的私有成员来减少一个不必要的函数,从而改进封装。

最新更新