运算符重载的概念:对已有的运算符重新定义,赋予另外的功能,以适应不同的数据类型,如自定义的数据类型。
这篇博客主要记录学习加号运算符重载、赋值运算符、关系运算符重载、函数调用运算符重载的过程。
1.加号运算符重载
作用:实现两个自定义数据类型相加的运算。
实现方式有两种,分别为成员函数实现和全局函数实现。
class Person{
public:
Person(){};
Person(int a,int b){
this->m_a=a;
this->m_b=b;
}
// 成员函数实现+号运算符重载
Person operator+(const Person& p){
Person tmp;
tmp.m_a=this->m_a+p.m_a;
tmp.m_b=this->m_b+p.m_b;
return tmp;
}
public:
int m_a;
int m_b;
};
//全局函数实现+号运算符重载
Person operator+(const Person& p1,const Person& p2){
Person tmp;
tmp.m_a=p1.m_a+p2.m_a;
tmp.m_b=p1.m_b+p2.m_b;
return tmp;
}
void test01(){
Person p1(2,5);
Person p2(6,4);
// 成员函数方式,相当于p1.operator+(p2)
// 全局函数方式,相当于operator+(p1,p2)
Person p3=p1+p2;
cout<<p3.m_a<<"---"<<p3.m_b<<endl;
}
2.赋值运算符重载
如果类中有属性在堆区开辟,而编译器提供的是浅拷贝,所以做赋值操作时会出现深浅拷贝的问题,此时需要重载赋值运算符。
class Student{
public:
Student(int age){
m_age=new int(age);
}
// 重载赋值运算符
Student& operator=(Student &student){
if(m_age!=NULL){
delete m_age;
m_age=NULL;
}
// 提供深拷贝,解决浅拷贝的问题
m_age=new int(*student.m_age);
// 返回自身
return *this;
}
~Student(){
if(m_age!=NULL){
delete m_age;
m_age=NULL;
}
}
public:
int *m_age;
};
void test01(){
Student student1(24);
Student student2(15);
student2=student1;
cout<<"student1的年龄:"<<*student1.m_age<<endl;
cout<<"student2的年龄:"<<*student2.m_age<<endl;
}
3.关系运算符重载
作用:让两个自定义的数据类型进行对比操作。
class Student{
public:
Student(string name,int age){
this->m_name=name;
this->m_age=age;
}
// 重载==运算符
bool operator==(Student &student){
if(this->m_name==student.m_name&&this->m_age==student.m_age){
return true;
}else{
return false;
}
}
// 重载!=运算符
bool operator!=(Student &student){
if(this->m_name==student.m_name&&this->m_age==student.m_age){
return false;
}else{
return true;
}
}
public:
string m_name;
int m_age;
};
void test01(){
Student student1("li",20);
Student student2("wang",20);
if(student1==student2){
cout<<"student1和student2相等"<<endl;
}else{
cout<<"student1和student2不相等"<<endl;
}
if(student1!=student2){
cout<<"student1和student2不相等"<<endl;
}else{
cout<<"student1和student2相等"<<endl;
}
}
4.函数调用运算符重载
函数调用运算符()可以发生重载,因为重载后的使用方式和函数的使用方式相似,所以称为仿函数。
class Myadd{
public:
int operator()(int a,int b){
return a+b;
}
};
void test01(){
Myadd myadd;
int result=myadd(5,6);
cout<<"result="<<result<<endl;
// 匿名对象调用,匿名对象当前行代码执行完后立即执行销毁操作
int res=Myadd()(20,30);
cout<<"res="<<res<<endl;
}