+= 运算符重载,但 use 不会编译,因为它看到一个简单的 +操作员
我已经重载了 + 和 += 运算符,并具有以下签名:
// within A's header file..
A operator+(const B &p);
A &operator+=(B &p);
为什么当我尝试使用 += 运算符时,我收到编译器错误消息
类型“A*”和的无效操作数 “B*”到二进制“运算符+”。
an_a; // an instance of class A
B *a_b = new B(some_parameters);
an_a += a_b;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您重载了
B&
的运算符。您试图向它传递一个指针,而不是 B 的实例或对 B 的引用。以下内容应该编译:an_a += *a_b;
,尽管更可能的修复是:还要注意动态分配和算术运算符重载不能很好地结合在一起。如果只是动态分配的输入,那可能没问题。只是不要尝试使用
new
分配结果并将其作为指针返回,否则您会发现为了避免内存泄漏,调用代码不能使用任何简单的表达式,这些表达式是您首先想要运算符重载的原因。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: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.您的错误信息与代码中的注释不一致。看起来
an_a
和a_b
都是指针,因此您必须取消引用它们才能使用运算符:*an_a += *a_b;
。另请注意,您的
operator+=
通过非常量引用获取B
。如果您将右侧参数更改为该运算符,有时有人会感到非常惊讶和不高兴。改为const
引用。Your error message is inconsistent with the comments in your code. It looks like both
an_a
anda_b
are pointers, so you have to dereference them to use operators:*an_a += *a_b;
.Also note that your
operator+=
takesB
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 itconst
reference instead.