运算符重载搜索概念

operator overloading seeking concept

本文关键字:搜索 重载 运算符      更新时间:2023-10-16
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 + intint += int

但是,为了完整起见,对于诸如A + B之类的操作,重载分辨率为

  1. A.operator+(B)
  2. 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+=