- 加号运算符重载
#include <iostream>
using namespace std;
class Person
{
public:
// 成员函数实现运算符重载
// Person operator+(Person &p)
// {
// Person temp;
// temp.a = this->a + p.a;
// temp.b = this->b + p.b;
// return temp;
// }
int a;
int b;
};
// 全局函数实现运算符重载
Person operator+(Person &p1, Person &p2)
{
Person temp;
temp.a = p2.a + p1.a;
temp.b = p2.b + p1.b;
return temp;
}
int main()
{
Person p1;
p1.a = 10;
p1.b = 20;
Person p2;
p2.a = 30;
p2.b = 40;
Person p3 = p1 + p2;
// 成员函数重载本质
// Person p3 = p1.operator+(p2);
// 全局函数重载本质
// Person p3 = operator+(p1, p2);
cout << p3.a << endl
<< p3.b << endl;
return 0;
}
- 左移运算符重载
左移运算符只能利用全局函数重载
#include <iostream>
using namespace std;
class Person
{
friend ostream &operator<<(ostream &cout, Person &p);
public:
Person(int a, int b)
{
this->m_A = a;
this->m_B = b;
}
private:
int m_A;
int m_B;
};
// 全局函数实现左移运算符重载
ostream& operator<<(ostream& cout, Person& p) {
cout << "a:" << p.m_A << " b:" << p.m_B;
return cout;
}
int main()
{
Person p1(10,20);
cout << p1 << endl;
return 0;
}
- 递增运算符重载
#include <iostream>
using namespace std;
class MyInteger
{
friend ostream &operator<<(ostream &cout, MyInteger myint);
public:
MyInteger() {
m_Num = 0;
}
// 前置++
MyInteger& operator++() {
m_Num++;
return *this;
}
// 后置++
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;
cout << myInt << endl;
}
// 后置++ 先返回 再++
void test02()
{
MyInteger myInt;
cout << myInt++ << endl;
cout << myInt << endl;
}
int main()
{
// test01();
test02();
return 0;
}
- 赋值运算符重载
利用深拷贝解决浅拷贝的问题。
#include <iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
m_Age = new int(age);
}
Person &operator=(Person &p)
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
// 深拷贝
m_Age = new int(*p.m_Age);
// 返回自身
return *this;
}
~Person()
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
int *m_Age;
};
int main()
{
Person p1(18);
Person p2(20);
Person p3(30);
p3 = p2 = p1; // 赋值操作
cout << "p1的年龄为:" << *p1.m_Age << endl;
cout << "p2的年龄为:" << *p2.m_Age << endl;
cout << "p3的年龄为:" << *p3.m_Age << endl;
return 0;
}