概念:对已有运算符进行重新定义,赋予其新功能,以适应不同的数据类型。
+运算符重载
#include<iostream>
#include<math.h>
using namespace std;
class Person
{
public:
//成员函数重载+
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;
};
//全局函数重载+
//Person operator+(Person& p1, Person& p2)
//{
// Person temp;
// temp.m_a = p1.m_a + p2.m_a;
// temp.m_b = p1.m_b + p2.m_b;
// return temp;
//}
void test01()
{
Person p1;
p1.m_a = 10;
p1.m_b = 10;
Person p2;
p2.m_a = 10;
p2.m_b = 10;
//成员函数本质调用
Person p3 = p1.operator+(p2);
//全局函数本质调用
/*Person p3 = operator+(p1, p2);*/
//简化形式
//Person p3 = p1 + p2;
cout << "p3.m_a=" << p3.m_a<<endl;
cout << "p3.m_b=" << p3.m_b << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
<<运算符重载
#include<iostream>
#include<math.h>
using namespace std;
class Person
{
public:
//不能利用成员函数实现<<重载,因为无法实现cout在左侧
int m_a;
int m_b;
};
//全局函数重载<<
//ostream对象只能有一个
ostream &operator<<(ostream &cout,Person p1)
{
cout << "m_a=" << p1.m_a << "m_b=" << p1.m_b << endl;
//返回cout才能实现<<无线追加
return cout;
}
void test01()
{
Person p1;
p1.m_a = 10;
p1.m_b = 10;
cout << p1 << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
递增运算符重载
通过递增运算符,实现自己的整形数据。
class MyInteger
{
friend ostream& operator<<(ostream& cout, MyInteger myint);//友元
public:
MyInteger()
{
m_num=0;
}
//重载前置++ 返回引用是为了对一个数据进行操作
MyInteger& operator++()
{
//先自增
m_num++;
//再返回自身
return *this;
}
//重载后置++ int代表占位参数用于区分前置和后置递增
MyInteger& operator++(int )
{
//先记录当时结果
MyInteger temp = *this;
//递增
m_num++;
//将记录结果返回
return temp;
}
private:
int m_num;
};
//重载<<
ostream& operator<<(ostream& cout, MyInteger myint)
{
cout << myint.m_num;
return cout;
}
void test01()
{
MyInteger myint;
cout << ++myint << endl;
}
void test02()
{
MyInteger myint;
cout << myint++ << endl;
cout << myint << endl;
}
赋值运算符重载
运算符重载