运算符重载概念:对已有的运算符重现定义,赋予其另一种功能,以适应不同的数据类型。

对于内置类型,编译器知道如何进行运算。

运算符重载也可以发生函数重载

1.加号运算符重载

作用:实现两个自定义数据类型相加的运算。

1.成员函数重载+号

class person

{

public:

//1.成员函数重载+号

person operator+(person& p)

{

 person temp;

 temp.m_a = this->m_a + p.m_a;

 temp.m_b = this->m_b + p.m_b;

 return temp;

}

int m_a;

int m_b;

};


void test()

{

person p1;

p1.m_a = 10;

p1.m_b = 10;

person p2;

p2.m_a = 20;

//成员函数重载本质调用

//person p3 = p1.operator+(p2);

   //简化后


person p3 = p1 + p2;

cout << "p3.m_a=" << p3.m_a << endl << "p3.m_b=" << p3.m_b << endl;

}


int main()

{

test();

system("pause");

return 0;

}


2.全局函数进行重载

person operator+ (person& p, person& p1)是全局函数

person operator+ (person& p, person& p1)

{

person temp;

temp.m_a = p1.m_a + p.m_a;

return temp;

}


//全局函数重载的本质调用

person p3 = operator+(p1, p2);

//简化后

//person p3 = p1 + p2;


递增运算符的调用

作用:通过重载递增运算符,实现自己的整形数据。

总结:前置递增返回引用,后置递增返回值。

例子:

#include <iostream>

using namespace std;


//递增运算符重载


class num

{

//前置++

//friend  ostream & operator<<(ostream& cout, num& p);


//后置++  

friend  ostream & operator<<(ostream& cout, num p);

 

public:

num()

{

 m_num = 0;

}


//重载前置++运算符

num &operator++()

{

 //先进行++运算 ,返回引用为了一直对一个数据进行递增操作

 m_num++;

 //再将自身返回

 return *this;

}


//重载后置++运算符

//void operator++(int)  int代表占位参数,用于区分前置和后置递增

//后置递增返回 值

num operator++(int)

{

 //先记录当前结果

 num temp=*this;

 


 //后递增

 m_num++;


 //最后将记录结果返回

 return temp;


}


private:

int m_num;

};


//创建前置++左移运算符重载

//ostream & operator<<(ostream& cout, num& p)

//{

// cout  << p.m_num;

// return cout;

//}


//创建后置++左移运算符重载

//因为是值传递  所以p不需要引用

ostream& operator<<(ostream& cout, num p)

{

cout << p.m_num;

return cout;

}


void test()

{

num Init;

cout<<++(++Init) << endl;

cout << Init << endl;

}


void test2()

{

num Init2;

cout << Init2++ << endl;

cout << Init2 << endl;


}

int main()

{

//test();

test2();

system("pause");

return 0;

}


赋值运算符重载

c++编译器至少各一个类添加4个函数

1.默认构造函数(无参,函数体为空)

2.默认析构函数(无参,函数体为空)

3.默认拷贝构造函数,对属性进行值拷贝

4.赋值运算符 operator=,对属性进行值拷贝。

如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题。


关系运算符

作用:重载关系运算符,可以让两个自定义对象进行对比操作。


函数调用运算符重载

1.函数调用运算符()也可以重载

2.由于重载后使用的方式非常像函数的调用,因此称为仿函数。

3.仿函数没有固定写法,非常灵活。