运算符重载
重载的概念:
对已有的运算符进行重新的定义,赋予其另一种功能,以适应不同的数据类型。
加号运算符重载
对于内置数据类型,编译器知道如何进行运算
c++
int a = 10;
int b = 20;
int c = a + b
可是自己定义的类并无法直接运算
C++
class Person
{
public:
int m_a;
int m_b;
}
Person p1
p1.m_a = 10;
p1.m_b = 10;
Person p2
p2.m_a = 20;
p2.m_b = 20;
Person p3 = p1 + p2;//这段代码编译器并不知道应该如何运算
如果是自己写成员函数的话;
c++
Person PaddP (Person &b)
{
Person temp;
temp.m_a = this->m_a + b.m_a;
temp.m_b = this->m_b + b.m_b;
return tamp;
}
编译器提供了一个通用名称--operator+
通过成员函数重载运算符:
C++
Person operator+ (Person &b)
{
Person temp;
temp.m_a = this->m_a + b.m_a;
temp.m_b = this->m_b + b.m_b;
return tamp;
}
通过全局函数重载运算符:
c++
Person operator+ (Person &p1 , Preson &p2)
{
Person temp;
temp.m_a = p1.m_a + p2.m_a;
temp.m_b = p1.m_b + p2.m_b;
return temp;
}
运算符重载函数也可以函数重载
左移运算符重载
作用可以输出自定义的数据类型
c++
ostream & operator<<(ostream &cout,Person &p)
{
cout <<"m_a="<<p.m_a<<"m_b"<<p.m_b;
return cout;
}
这样"<<"运算符号就被重载了
递增重载运算符++
首先我们需要明白++运算符的原理
C++
int a = 10;
cout << ++a << endl;//输出11
cout << a <<endl;//输出11
int b = 10;
cout << b++ << endl;//输出10
cout << b << endl;//输出11
重载分为两种
- 前置重载
- 后置重载
前置如下:
C++
//在成员函数内
//首先需要上面所写的<<重载
ostream& operator<<(ostream &cout,Person &p)
{
cout <<"m_a="<<p.m_a<<"m_b"<<p.m_b;
}
//重载++(这是在class内中)
Person& operator++ ()
{
m_a++;
m_b++;
return *this;
}
后置重载
c++
Person operator++(int)//int代表展位参数,可以区分前置和后置递增
{
//先 记录当时结果
Person temp = *this;
//后 递增
m_a++;
m_b++;
//最后将记录结果返回
return temp;
}
赋值运算符重载
c++编译器至少给一个类添加四个函数
- 默认函数构造(无参,函数体为空)
- 默认析构函数(无参,函数体为空)
- 默认拷贝构造函数,对属性进行拷贝
- 赋值运算符
operator=
对属性进行拷贝
如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝的问题.
写法与深拷贝类似
c++
Person& operator=(person &p)
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
m_Age= new int(*m_Age);
return *this;
}
关系运算符重载
重载==:
c++
//在成员函数内
bool operator== (const Person &p)
{
if (this->m_Name == p.m_name && this->m_Age == p.m_Age)
{
return true;
}
return false;
}
重载!=:
c++
//在成员函数内
bool operator!= (const Person &p)
{
if (this->m_Name == p.m_name && this->m_Age == p.m_Age)
{
return false;
}
return true;
}
函数调用运算符重载
- 函数调用运算符()。也可以重载
- 对于重载后非常像函数的调用,因此称为仿函数
- 仿函数没有固定写法十分灵活
匿名函数对象
首先是匿名对象,其次是仿函数