运算符重载搜索概念
operator overloading seeking concept
class A{
..........
..........
};
int x;
A a;
x=a + x; // option 1
x=x + a; // option 2
x+=a; // option 3
所有选项 1 2 和 3 的运算符 + 重载会相同吗?即int A::operator+(int s(
如果不是为什么,对其他人来说是什么?
No.
这将调用A::operator +(int)
或operator +(A, int)
:
x=a + x; // option 1
这将调用operator +(int, A)
(没有int::operator +(A)
这样的东西(:
x=x + a; // option 2
这将调用operator +=(int, A)
(但你最好将第一个参数A&
,而不仅仅是A
否则你实际上将无法编写一个工作+=
运算符(。没有int::operator +=(A)
这样的东西:
x+=a; // option 3
他们之所以称不同的运算符重载,是因为它们不同......不知道还能告诉你什么。
根本不需要运算符重载,因为您基本上会执行int + int
或int += int
。
但是,为了完整起见,对于诸如A + B
之类的操作,重载分辨率为
-
A.operator+(B)
-
operator+(A, B)
对于+=
来说,它是不同的,因为它是一个单独的运算符,operator+=
.它不能有任何非成员重载(没有赋值运算符可以(,因此对于A += B
,唯一可能的尝试是A.operator+=(B)
。
编辑后,选项 1 仍处于A.operator(x)
或operator+(A, x)
状态(如上所述(。
选项 2 不能有成员重载,因此唯一可行的变体是 opetrator+(x, A)
或 x + static_cast<int>(A)
。
选项 3 只能x += static_cast<int>(A)
。
static_cast<int>(A)
选项将使用operator int
重载。如果不存在,那么这些替代方案是不可能的,并且在构建时会出现错误。
我还建议例如这个运算符重载引用。当然,你读了几本好书。
在你的例子中,如果你喜欢A::operator+(int s)
,那么这个重载对x+a
不起作用,除非你定义一个像operator int()
这样的类型转换。因为作为成员operator +
函数将隐式this
指针作为rhs
参数。
因此,建议将operator +
作为非成员函数重载。如有必要,提供隐式类型转换,如 operator int()
或 A(int)
;
一旦你决定重载operator+
,建议也提供operator+=
,以便*,/,-
。因为编译器不会自动为您生成operator+=
。
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 有根的二进制搜索树.保留与其父级的链接
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- 在C++中搜索嵌套多映射值
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 正在尝试重载二进制搜索树分配运算符
- 运算符重载搜索概念
- 二叉搜索树<<运算符重载不起作用
- 使用二进制搜索树重载运算符
- std::ostringstream 运算符重载搜索顺序
- 二叉搜索树重载==操作符或只需要一般建议