除了 'new'、'delete'、'<<' 和 '>>' 运算符外,还有哪些其他运算符可以在类上下文之外的 C++ 中重载?
最佳答案
以下运算符(以空格分隔)可以作为非成员函数重载:
new delete new[] delete[] + - * / % ˆ & | ˜ ! < > += -= *= /= %= ˆ=
&= |= << >> >>= <<= == != <= >= && || ++ -- , ->*
以下必须是非静态成员函数:
-> () [] =
以下不能重载:
. .* :: ?: # ##
转换运算符也必须是成员函数。
仅仅因为它有一个'='并不意味着它不能作为非成员运算符被重载。以下是格式正确的:
struct A { };
A operator +=(A,A) { return A(); }
A a = A()+=A();
而且前缀和后缀自增自减运算符确实可以定义为非成员:
13.5.7 The user-defined function called operator++ implements the prefix and postfix ++ operator. If this function is a member function with no parameters, or a non-member function with one parameter of class or enumeration type, it defines the prefix increment operator ++ for objects of that type. If the function is a member function with one parameter (which shall be of type int) or a non-member function with two parameters (the second of which shall be of type int), it defines the postfix increment operator ++ for objects of that type. When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero.
The prefix and postfix decrement operators -- are handled analogously
标准中的第 13.5 条涵盖了这一点。
希望这对您有所帮助。
关于c++ - C++中的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1448596/