实现一个操作符重载的方式通常有两种情况:
- 将操作符重载实现为类的成员函数。
- 操作符重载实现为非类的成员函数(即全局函数)。
- 将操作符重载实现为类的成员函数
在类体中声明(定义)需要重载的操作符,声明方式跟普通的成员函数一样,只不过操作符重载函数的名字是“关键字operator +以及紧跟其后的一个C++预定义的操作符”。参数则需要传入除自己以外的别的参数(比如==需要两个参数,即自身和另一个对象,因此传入另一个对象即可,自身就是this)。
形式即如下(Student为自定义类):
1
| bool operator==(const Student &student){}
|
此处要注意输入输出操作(<< and >>)的重载方式有所不同,需要使用友元函数,形式如下:
1
| friend ostream &operator<<(ostream &os, const Student &student)
|
- 操作符重载实现为非类的成员函数
对于全局重载操作符,代表左操作数的参数必须被显式指定。
形式如下:
1
| bool operator>(Student &student, Student &student1)
|
可以根据以下因素,确定把一个操作符重载为类的成员函数还是全局函数:
- 如果一个重载操作符是类成员,那么只有当与它一起使用的左操作数是该类的对象时,该操作符才会被调用;而如果该操作符的左操作数确定为其他的类型,则操作符必须被重载为全局函数;
- C++要求’=’、’[]’、’()’、’->’操作符必须被定义为类的成员操作符,把这些操作符通过全局函数进行重载时会出现编译错误
- 如果有一个操作数是类类型(如string类),那么对于对称操作符(比如==操作符),最好通过全局函数的方式进行重载。
实现操作符重载时,需要注意有如下限制:
- 重载后操作符的操作数至少有一个是用户定义类型;
- 不能违反原来操作数的语法规则;
- 不能创建新的操作符;
- 不能重载的操作符包括(以空格分隔):sizeof . .* :: ?: RTTI类型运算符
=、()、[]、以及 ->操作符只能被类的成员函数重载
下面给出示例代码,其中使用全局函数的为重载>。
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| #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 &operator++() { sno++; return *this; }
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; }
|
结果如下: