有没有办法在动态 C++ 中使用运算符重载?目的

发布于 2024-12-18 20:21:00 字数 44 浏览 2 评论 0原文

我想在 C++ 中对动态对象使用运算符重载,

我该怎么做?

I want to use operator overloading with dynamic object in C++

how can i do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

唠甜嗑 2024-12-25 20:21:00

我认为动态对象是指创建到堆的对象,因此它们被作为指针引用。你是对的,对此类对象使用重载运算符并不像本地对象那么舒服。但这是可能的。它看起来很糟糕。因为我们谈论的是 C++,所以有不止一种方法可以做到这一点。

假设我们有一个名为 Irrational 的类,它重载了 += 运算符,您可以这样做:

Irrational* a = new Irrational(2,-4);
a->operator+=(3);

Irrational* b = new Irrational(2,-4);
(*b) += 3;

因此,可以通过使用“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:

Irrational* a = new Irrational(2,-4);
a->operator+=(3);

Irrational* b = new Irrational(2,-4);
(*b) += 3;

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.

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