简体   繁体   中英

+= operator overloaded, but use won't compile since it sees a simple + operator

I have overloaded both the + and += operator, with the following signatures:

// within A's header file..
A operator+(const B &p);    
A &operator+=(B &p);

Why is it that when I try to use the += operator, I get the compiler error message

Invalid operands of types "A*" and "B*" to binary 'operator+'.

an_a; // an instance of class A
B *a_b = new B(some_parameters);
an_a += a_b;

You overloaded the operator for B& . You're trying to pass it a pointer, not an instance of B or reference to B. The following should compile: an_a += *a_b; , although a more likely fix is:

A an_a(some parameters);
B a_b(some parameters);
an_a += a_b;

Also beware that dynamic allocation and arithmetic operator overloading don't play especially nicely together. If it's only the inputs that are dynamically allocated it's probably fine. Just don't try to allocate the result with new and return it as a pointer, or you'll find that in order to avoid memory leaks the calling code can't use any of the simple expressions that were the reason you wanted operator overloading in the first place.

Your error message is inconsistent with the comments in your code. It looks like both an_a and a_b are pointers, so you have to dereference them to use operators: *an_a += *a_b; .

Also note that your operator+= takes B by non-const reference. If you're changing the right-hand argument to that operator someone is going to be very surprised and unhappy sometime. Make it const reference instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM