为什么运算符有时是独立的,有时是类方法?
为什么有时运算符重写被定义为类中的方法,例如
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有像 + 这样的二元运算符,您通常希望对两个操作数执行类型转换。例如,字符串连接运算符需要能够将其一个或两个操作数从 char * 转换为字符串。如果是这种情况,那么它不能是成员函数,因为左侧操作数将是 *this,并且不会执行转换。
例如:
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.:
如果运算符是在类外部定义的,则它被视为全局的,并允许您让其他类型出现在运算符的左侧。
例如,给定一个类
Foo
,使用全局运算符+
你可以这样做: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:如果您希望能够执行类似
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