目录
-
操作符重载函数是什么
operator 是C++的一个关键字,它和运算符(如=)一起使用,表示一个运算符重载函数,在理解时可将operator和运算符(如operator=)视为一个函数名。
使用operator重载运算符,是C++扩展运算符功能的方法。使用operator扩展运算符功能的原因如下:
使重载后的运算符的使用方法与重载前一致
扩展运算符的功能只能通过函数的方式实现(实际上,C++中各种“功能”都是由函数实现的)
-
操作符重载函数,是编译时多态的一种体现。
-
操作符重载函数的实现又分为:类的成员函数,非类的成员函数。
-
举例 ==重载函数
作为类的成员函数:
bool operator==(const person& ps)
{
if (this->age == ps.age)
{
return true;
}
return false;
}
//示例代码(operator_test2.cpp)如下:
#include <iostream>
using namespace std;
class person
{
private:
int age;
public:
person(int nAge)
{
this->age = nAge;
}
bool operator==(const person& ps)
{
if (this->age == ps.age)
{
return true;
}
return false;
}
};
int main()
{
person p1(10);
person p2(10);
if (p1 == p2)
{
cout << "p1 is equal with p2." << endl;
}
else
{
cout << "p1 is not equal with p2." << endl;
}
return 0;
}
作为非类的成员函数:
#include <iostream>
using namespace std;
class person
{
public:
int age;
};
// 左操作数的类型必须被显式指定
// 此处指定的类型为person类
bool operator==(person const& p1 ,person const& p2)
{
if (p1.age == p2.age)
{
return true;
}
else
{
return false;
}
}
int main()
{
person p1;
person p2;
p1.age = 18;
p2.age = 18;
if (p1 == p2)
{
cout << "p1 is equal with p2." << endl;
}
else
{
cout << "p1 is NOT equal with p2." << endl;
}
return 0;
}