有没有办法在动态 C++ 中使用运算符重载?目的
我想在 C++ 中对动态对象使用运算符重载,
我该怎么做?
I want to use operator overloading with dynamic object in C++
how can i do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我想在 C++ 中对动态对象使用运算符重载,
我该怎么做?
I want to use operator overloading with dynamic object in C++
how can i do it?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
我认为动态对象是指创建到堆的对象,因此它们被作为指针引用。你是对的,对此类对象使用重载运算符并不像本地对象那么舒服。但这是可能的。它看起来很糟糕。因为我们谈论的是 C++,所以有不止一种方法可以做到这一点。
假设我们有一个名为 Irrational 的类,它重载了 += 运算符,您可以这样做:
因此,可以通过使用“operator”前缀来调用堆对象的重载运算符,在这种情况下,它很像函数调用,或者首先将指针转换为引用,在这种情况下它工作得更“正常”。就是这样。
I think by dynamic object you mean objects created to heap, so they are referenced as pointers. You are right, using overloaded operators for such objects is not as comfortable as local objects. But it is possible. And it looks terrible. And because we are talking about C++, there's more than one way to do it.
Let's say we have a class called Irrational, which overloads the += operator, you can do:
So a heap object's overloaded operator is called either by calling it with the "operator" prefix, in which case it is a lot like a function call, or by converting the pointer first to a reference, in which case it works more "normally". That's it.