代码仓库shanchuann/CPP-Learninng

在C++中,operator关键字用于定义和重载运算符,使得自定义类的对象可以使用标准运算符进行操作,从而提高代码的可读性和可维护性。

运算符重载的基本概念

  • 作用operator主要有两个作用,一是操作符的重载,二是操作符的转换。操作符重载是对C++进行扩展,让自定义类的对象能够像内置类型一样使用运算符。
  • 可重载与不可重载的操作符:可重载的操作符包括+-*/%^&|~!=<>等;不可重载的操作符有..*::?:等。

运算符重载的语法

运算符重载通过定义一个特殊的成员函数或友元函数来实现,其基本语法为:返回类型 operator 运算符 (参数列表)。例如,重载+运算符:

1
2
3
4
5
6
7
8
9
class Complex {
public:
double real, imag;
Complex(double r, double i) : real(r), imag(i) {}
// 重载 + 运算符
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
};
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
class Int {
private:
int* value;
public:
// 构造函数
Int(int v) : value(new int(v)) {
cout << "Create Int at " << this << endl;
}
// 自定义拷贝构造函数(深拷贝)
Int(const Int& other) : value(new int(*other.value)) {
cout << "Copy Create Int at " << this << endl;
}
// 析构函数
~Int() {
delete value;
cout << "Destroy Int at " << this << endl;
}

Int operator+(const Int& it) const{ //对象 + 对象
int tmp = this->value + it.value;
return Int(tmp);
}
Int operator+(const int x) const{ //对象 + 变量
return Int(x + this->value);
}
};
Int operator+(const int x,const Int& it){ //变量 + 对象
return it + x;
}

运算符重载的实现方式

  • 作为类的成员函数:在类体中声明和定义需要重载的操作符,如bool operator==(const person& ps),只有当与它一起使用的左操作数是该类的对象时,该操作符才会被调用。=()[]->操作符必须被定义为类的成员操作符。
  • 作为全局函数:对于全局重载操作符,代表左操作数的参数必须被显式指定。如果有一个操作数是类类型,对于对称操作符,最好通过全局函数的方式进行重载。例如:
1
2
3
4
5
6
7
8
9
10
class person {
public:
int age;
};
bool operator==(person const& p1, person const& p2) {
if (p1.age == p2.age) {
return true;
}
return false;
}
  • 作为类的友元函数:一个类的friend函数可以访问该类的私有成员和保护成员,可用于重载操作符。例如,重载插入运算符<<通常使用友元函数:
1
2
3
4
5
6
7
8
9
10
class Complex {
public:
double real, imag;
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
friend ostream& operator<<(ostream& os, const Complex& c);
};
ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c.real << ", " << c.imag << ")";
return os;
}
  • 重载后操作符的操作数至少有一个是用户定义类型。
  • 不能违反原来操作数的语法规则,不能创建新的操作符。
  • 基类对赋值操作符(=)重载不能被派生类继承。

特殊运算符的重载

operator++为例,C++允许重载incrementdecrement操作符的两种形式,前缀形式返回一个引用,后缀形式返回一个const类型。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class UPInt {
public:
UPInt& operator++(); // ++前缀
const UPInt operator++(int); // ++后缀
};
UPInt& UPInt::operator++() {
// 前缀自增的实现
return *this;
}
const UPInt UPInt::operator++(int) {
UPInt temp = *this;
// 后缀自增的实现
return temp;
}