简介
operator重载运算符,例如"operator="可以看作是一个函数名,重载后的使用前后保持一致;
重载方式
类的成员函数
声明方式和普通函数一样,运算符重载函数为“关键字operator加上预定义的操作”,实现如下所示:
class Person {
private:
int age;
public:
Person(int age) {
this->age = age;
}
bool operator==(const Person &person) {
if (this->age == person.age) {
cout << "equal." << endl;
return true;
} else {
cout << "not equal." << endl;
return false;
}
}
};
int main(int args, char **argv) {
Person p1(10);
Person p2(10);
if (p1 == p2) { // 相当于调用了operator==这个函数,把p2作为参数传递给该函数,然后实现了函数内部的逻辑处理,p1为当前函数this
cout << "p1 is equal with p2." << endl;
} else {
cout << "p1 is not equal with p2." << endl;
}
return 0;
}
输出结果如下所示
xxx:/system/bin # ./hello_test
equal.
p1 is equal with p2.
全局函数
全局重载运算符,代表左操作数的参数必须“显示”出现。
class Person {
public:
int age;
};
bool operator==(Person &p1, Person &p2) {
if (p1.age == p2.age) {
cout << "global equal." << endl;
return true;
} else {
cout << "global not equal." << endl;
return false;
}
}
int main(int args, char **argv) {
Person p1;
p1.age = 18;
Person p2;
p2.age = 18;
if (p1 == p2) {
cout << "p1 is equal with p2." << endl;
} else {
cout << "p1 is not equal with p2." << endl;
}
return 0;
}
输出结果如下所示
xxx:/system/bin # ./hello_test
global equal.
p1 is equal with p2.
总结
1.当重载运算符是类的成员函数,只有左操作运算符是该类的对象时,运算符才会被调用;若左操作是其他类型,则运算符必须被重载为全局函数;
2.C++中要求以下运算符须定义为类的成员函数,否则就会报错;
=、[]、()、->