C++ 中的运算符重载
除了“新建”、“删除”、“<<” & '>>'运算符,还有哪些其他运算符可以在类上下文之外的 C++ 中重载?
Besides 'new', 'delete', '<<' & '>>' operators, what other operators can be overloaded in C++ outside of a class context?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下运算符(由空格分隔)可以作为非成员函数重载:
以下运算符必须是非静态成员函数:
以下运算符不能重载:
转换运算符也必须是成员函数。
仅仅因为它有一个“=”并不意味着它不能作为非成员运算符重载。以下是格式良好的:
并且前缀和后缀递增和递减运算符确实可以定义为非成员:
标准中的第 13.5 条涵盖了这一点。
希望这有帮助。
The following operators (delimitted by space) can be overloaded as non-member functions:
The following have to be non-static member functions:
The following can not be overloaded:
conversion operators also have to be member functions.
And just because it has a '=' in it does not mean it cannot be overloaded as a non-member operator. The following is well-formed:
And the prefix and postfix increment and decrement operators can indeed be defined as non-members:
Clause 13.5 in the Standard covers this.
Hope this helps.
可重载的运算符(逗号用作分隔符):
+、-、*、/、%、^、&、|、~、!、=、<、>、+=、-=、 *=、/=、%=、^=、&=、|=、>>=、<<=、
!=、<=、>=、&&、||、++、--、->*、(即逗号运算符)、->、[]、()、new[] 、delete[]
不能重载的运算符:
., .*, ::, ?:
重载函数必须声明为类方法的运算符:
()、[]、->、任何赋值运算符
(正如评论者指出的)
Operators that can be overloaded (comma used as delimiter):
+, -, *, /, %, ^, &, |, ~, !, =, <, >, +=, -=, *=, /=, %=, ^=, &=, |=, >>=, <<=,
!=, <=, >=, &&, ||, ++, --, ->* , (i.e., comma operator), ->, [], (), new[], delete[]
Operators that can not be overloaded:
., .*, ::, ?:
Operators where overloading function must be declared as a class method:
(), [], ->, any assignment operator
(as the commenters noted)