+= 运算符重载,但 use 不会编译,因为它看到一个简单的 +操作员

发布于 2024-10-19 19:09:54 字数 359 浏览 1 评论 0原文

我已经重载了 + 和 += 运算符,并具有以下签名:

// 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

西瑶 2024-10-26 19:09:55

您重载了 B& 的运算符。您试图向它传递一个指针,而不是 B 的实例或对 B 的引用。以下内容应该编译:an_a += *a_b;,尽管更可能的修复是:

A an_a(some parameters);
B a_b(some parameters);
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:

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.

脸赞 2024-10-26 19:09:55

您的错误信息与代码中的注释不一致。看起来 an_aa_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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文