实现一个操作符重载的方式通常有两种情况:
- 将操作符重载实现为类的成员函数。
- 操作符重载实现为非类的成员函数(即全局函数)。
- 将操作符重载实现为类的成员函数
在类体中声明(定义)需要重载的操作符,声明方式跟普通的成员函数一样,只不过操作符重载函数的名字是“关键字operator +以及紧跟其后的一个C++预定义的操作符”。参数则需要传入除自己以外的别的参数(比如==需要两个参数,即自身和另一个对象,因此传入另一个对象即可,自身就是this)。
形式即如下(Student为自定义类):
bool operator==(const Student &student){}
此处要注意输入输出操作(<< and >>)的重载方式有所不同,需要使用友元函数,形式如下:
friend ostream &operator<<(ostream &os, const Student &student)
- 操作符重载实现为非类的成员函数
对于全局重载操作符,代表左操作数的参数必须被显式指定。
形式如下:
bool operator>(Student &student, Student &student1)
可以根据以下因素,确定把一个操作符重载为类的成员函数还是全局函数:
- 如果一个重载操作符是类成员,那么只有当与它一起使用的左操作数是该类的对象时,该操作符才会被调用;而如果该操作符的左操作数确定为其他的类型,则操作符必须被重载为全局函数;
- C++要求'='、'[]'、'()'、'->'操作符必须被定义为类的成员操作符,把这些操作符通过全局函数进行重载时会出现编译错误
- 如果有一个操作数是类类型(如string类),那么对于对称操作符(比如==操作符),最好通过全局函数的方式进行重载。
实现操作符重载时,需要注意有如下限制:
- 重载后操作符的操作数至少有一个是用户定义类型;
- 不能违反原来操作数的语法规则;
- 不能创建新的操作符;
- 不能重载的操作符包括(以空格分隔):sizeof . .* :: ?: RTTI类型运算符
=、()、[]、以及 ->操作符只能被类的成员函数重载
下面给出示例代码,其中使用全局函数的为重载>。
#include <iostream>
using namespace std;
class Student {
public:
int sno;
string name;
Student(int s = 0, string n = "") : sno(s), name(n) {}
bool operator==(const Student &student) {
if (sno == student.sno) return true;
return false;
}
// 将操作符重载实现为类的成员函数
bool operator<(const Student &student) {
if (sno < student.sno) return true;
return false;
}
// ++student 前缀形式
Student &operator++() {
sno++;
return *this;
}
// student++ 后缀形式
Student operator++(int) {
Student student(sno, name);
sno++;
return student;
}
friend ostream &operator<<(ostream &os, const Student &student) {
os << student.sno << " " << student.name;
return os;
}
friend istream &operator>>(istream &is, Student &student) {
cout << "input sno:";
is >> student.sno;
cout << "input name:";
is >> student.name;
return is;
}
};
// 操作符重载实现为非类的成员函数
bool operator>(Student &student, Student &student1) {
if (student.sno > student1.sno) return true;
return false;
}
int main() {
Student student_a;
cin >> student_a;
cout << "your input: " << student_a << endl;
Student student_b = student_a++;
cout << "student_a: " << student_a << endl;
cout << "student_b: " << student_b << endl;
cout << "student_a < student_b: " << (student_a < student_b) << endl;
cout << "student_a > student_b: " << (student_a > student_b) << endl;
cout << "student_a == student_b: " << (student_a == student_b) << endl;
cout << endl;
Student student_c = ++student_a;
cout << "student_a: " << student_a << endl;
cout << "student_c: " << student_c << endl;
cout << "student_a < student_c: " << (student_a < student_c) << endl;
cout << "student_a > student_c: " << (student_a > student_c) << endl;
cout << "student_a == student_c: " << (student_a == student_c) << endl;
}
结果如下:
![](https://img2020.cnblogs.com/blog/1659233/202103/1659233-20210307201305962-1946306568.png)