c++ - C++中的运算符重载

标签 c++ operator-overloading

除了 '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/

相关文章:

c++ - Windows 上的 clang 和 <iostream>

c++ - 尝试获取物理设备时出现Vulkan错误VK_ERROR_INITIALIZATION_FAILED

c++ - 类型特征修改后不能 const 限定类型

python - 使运算符在 python 中重载更少冗余?

c++ - 基本的新建/删除运算符(operator)日志记录

c++ - 为什么 '::' 、 '.' 、 '?:' 等运算符不能在 C++ 中重载?

c++ - void* 数组将元素转换为另一种类型

c++ - 在 dxdt 函数中使用 Eigen 和 Odeint 进行矩阵* vector 乘法

c++ - 模板转换运算符 C++

c++ - 是否有默认为静态的成员函数?