为什么运算符有时是独立的,有时是类方法?

发布于 2024-08-13 07:58:33 字数 288 浏览 6 评论 0原文

为什么有时运算符重写被定义为类中的方法,例如

MyClass& MyClass::operatorFoo(MyClass& other) { .... return this; };

有时它是一个单独的函数,例如

MyClass& operatorFoo(MyClass& first, MyClass& bar)

它们是否等效?当你以一种方式做事和以另一种方式做事时,有哪些规则适用?

Why is that sometimes an operator override is defined as a method in the class, like

MyClass& MyClass::operatorFoo(MyClass& other) { .... return this; };

and sometimes it's a separate function, like

MyClass& operatorFoo(MyClass& first, MyClass& bar)

Are they equivalent? What rules govern when you do it one way and when you do it the other?

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

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

发布评论

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

评论(3

梦巷 2024-08-20 07:58:34

如果您有像 + 这样的二元运算符,您通常希望对两个操作数执行类型转换。例如,字符串连接运算符需要能够将其一个或两个操作数从 char * 转换为字符串。如果是这种情况,那么它不能是成员函数,因为左侧操作数将是 *this,并且不会执行转换。

例如:

operator+( a, b );  // conversions performed on a and b
a->operator+( b );  // conversion can only be performed on b

If you have a binary operator like +, you normally want type conversions to be performed on both operands. For example, a string concatenation operator needs to be able to convert either or both of its operands from a char * to a string. If that is the case, then it cannot be a member function, as the left hand operand would be *this, and would not have a conversion performed.

E.g.:

operator+( a, b );  // conversions performed on a and b
a->operator+( b );  // conversion can only be performed on b
鹊巢 2024-08-20 07:58:34

如果运算符是在类外部定义的,则它被视为全局的,并允许您让其他类型出现在运算符的左侧。

例如,给定一个类 Foo,使用全局运算符 + 你可以这样做:

Foo f;
Foo f2 = 55 + f;

If the operator is defined outside of a class it's considered global, and allows you to have other types appear on the left hand side of the operator.

For example, given a class Foo, with a global operator + you could do:

Foo f;
Foo f2 = 55 + f;
糖果控 2024-08-20 07:58:33

如果您希望能够执行类似 3 + obj 的操作,则必须定义一个自由(非成员)运算符。

如果您想让您的操作员受到保护或私有,您必须将它们设置为方法。

有些运算符不能是自由函数,例如operator->

这里已经回答了这个问题:

全局运算符和成员运算符之间的区别

If you want to be able to do something like 3 + obj you have to define a free (non-member) operator.

If you want to make your operators protected or private, you have to make them methods.

Some operators cannot be free functions, e.g., operator->.

This is already answered here:

difference between global operator and member operator

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