Reputation: 35
I'm learn C++ (overloading operators if be precise). I try overload operator+ by this way:
Complex4d Complex4d::operator+(const Complex4d &rvalue)
{
return Complex4d(a() + rvalue.a(), b());
}
Where rvalue.a() and a(), rvalue.b() and b() it's object of the Complex2d. In Complex2d class I overload operator+ too, by this way:
Complex2d Complex2d::operator +(Complex2d &rvalue)
{
return Complex2d(a() + rvalue.a(), b() + rvalue.b());
}
If I write this:
Complex4d Complex4d::operator+(const Complex4d &rvalue)
{
Complex2d test = rvalue.a();
return Complex4d(a() + test, b());
}
All it's OK. What do i do wrong?
Upvotes: 2
Views: 148
Reputation: 61910
The problem is that you're trying to bind a temporary to a non-const reference, which is not allowed and makes no sense:
Complex2d Complex2d::operator +(Complex2d &rvalue)
^^^^^^^^^^^
return Complex4d(a() + rvalue.a(), b());
^^^^^^^^^^
To fix it, make it take a const reference, to which temporaries can be bound. Const-correctness also applies. If you're not modifying it (you shouldn't be), make it const
.
Complex2d Complex2d::operator +(const Complex2d &rvalue)
^^^^^
The other argument (*this
) isn't modified either:
Complex2d Complex2d::operator +(const Complex2d &rvalue) const
^^^^^ ^^^^^
As well, I suggest making them free functions and reusing other code:
Complex2d operator+(const Complex2d &lhs, const Complex2d &rhs) {
auto ret = lhs;
ret += rhs;
return ret; //see comments for implementation reasoning
}
This allows the left side to act the same as the right and improves encapsulation by having one less unnecessary function with access to the private members of the class.
Upvotes: 4