运算符重载小知识点

在 C++ 中,运算符重载可以通过成员函数或友元函数来实现。对于成员函数形式的运算符重载,输入参数的数量确实看起来只有一个,但实际上有两个参数:

隐式参数:即调用该运算符的对象本身。在成员函数中,这个对象可以通过 this 指针访问。
显式参数:即传递给成员函数的参数

1
2
3
Complex c1(3.5, 2.0);
Complex c2(1.0, 4.0);
Complex sum = c1 + c2;

在这个例子中,c1 + c2 实际上被编译器解释为 c1.operator+(c2)。这里:

c1 是隐式参数,对应 this 指针。
c2 是显式参数,传递给 operator+ 函数。
因此,虽然 operator+ 函数的定义中只有一个参数,但在实际调用时,c1 和 c2 都参与了运算。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
## 完整代码
#include <iostream>

class Complex {
private:
double real;
double imag;
public:
// 构造函数
Complex(double r = 0, double i = 0) : real(r), imag(i) {}

// 加法运算符重载
Complex operator+(const Complex& other) const {
Complex result;
result.real = this->real + other.real;
result.imag = this->imag + other.imag;
return result;
}

// 减法运算符重载
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}

// 输出运算符重载
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
};
int main() {
Complex c1(3.5, 2.0);
Complex c2(1.0, 4.0);

Complex sum = c1 + c2;
Complex diff = c1 - c2;

std::cout << "c1: " << c1 << std::endl;
std::cout << "c2: " << c2 << std::endl;
std::cout << "c1 + c2: " << sum << std::endl;
std::cout << "c1 - c2: " << diff << std::endl;

return 0;
}