1、为什么需要重载操作符?
c++中操作符包括==,>=, >>, << 等。比如==,c++中默认实现比较两个大小是否相等,但当要比较两个class变量是否相等,就要重载操作符==。例如:两个Person类的变量,只有当其age和sex一样时才是同一个人,这时候就需要重载操作符。
2、如何使用操作符?
operator是c++的关键字,要和运算符一起使用。应当把operator==看作一个整体。
2.1、类成员函数实现操作符重载
Person.h
#pragma once
#include <string>
using namespace std;
class Person
{
public:
Person();
~Person();
int age; //年龄
string sex; //性别
Person(int a,string b); //构造函数
bool operator==(Person p2) const; //比较两个人是否一样
};
Person.cpp
#include "Person.h"
Person::Person(){}
Person::~Person(){}
Person::Person(int a, string b)
{
this->age = a;
this->sex = b;
}
bool Person::operator==(Person p2) const //操作符重载
{
if (this->age == p2.age && this->sex == p2.sex)
{
return true;
}
return false;
}
main.cpp
#include "Person.h"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
Person p1(10, "boy");
Person p2(10, "boy");
if (p1 == p2)
cout << "p1和p2年龄相同" << endl;
else
cout << "p1和p2年龄不相同" << endl;
}
注意:p1==p2表示的是p1调用成员函数==,传入的参数为p2。
2.2、全局函数实现操作符重载
注意:对于全局重载操作符,代表左操作数的参数必须被显式指定
main.cpp
class Person
{
public:
int age;
string sex;
Person(int a, string b)
{
this->age = a;
this->sex = b;
}
};
bool operator==(Person p1, Person p2) //满足要求,做操作数的类型被显示指定
{
if(p1.age == p2.age && p1.sex == p2.sex)
return true;
return false;
}