Reputation: 13
I constantly got compilation error:
no match for ‘operator=’ in ‘bObj1 = Balance::operator+(Balance&)(((Balance&)(& bObj2)))’
Could you someone help to point out the reason? Thanks in advance.
code:
class Balance
{
public:
Balance (int b = 0) {balance = b;};
Balance (Balance &);
Balance & operator= (Balance &);
Balance operator+ (Balance &);
int get() {return balance;};
void set(int b) {balance = b;};
private:
int balance;
};
Balance & Balance::operator=(Balance ©)
{
balance = copy.get();
return *this;
}
Balance Balance::operator+ (Balance &rig)
{
Balance add;
add.set(this->get() + rig.get());
return add;
}
int main()
{
Balance bObj1, bObj2(100);
bObj1 = bObj2;
bObj1 = bObj1 + bObj2; // This line cause the error.
return 0;
}
Upvotes: 1
Views: 127
Reputation: 918
Your assigment operator is wrong. You can safety remove it, because implicit operator is enough for you simple class. Read When do I need to write an assignment operator? for more details.
class Balance
{
public:
Balance (int b = 0) {balance = b;};
Balance operator+ (const Balance &);
int get() const {return balance;};
void set(int b) {balance = b;};
private:
int balance;
};
Balance Balance::operator+ (const Balance &rig)
{
Balance add;
add.set(this->get() + rig.get());
return add;
}
Upvotes: 2
Reputation: 63451
You'll have issues when using operator overrides with non-const references. Change your functions to const:
Balance & operator= (const Balance &);
Balance operator+ (const Balance &) const;
int get() const { return balance; }
When the +
operator is applied, the result is an rvalue, which is immutable. Because your =
could not accept an rvalue
reference (because it was not const), the compiler was unable to match the operator.
Above, I've made your functions rvalue-friendly. The =
operator will accept an rvalue. The +
operator also accepts an rvalue and is const
because it doesn't modify the object. Because it is const, I've made the get
function const too.
Upvotes: 0