知识点1 可重载的运算符
知识点2 重载自增或者自减运算符++ — 运算符
operator++
编译器看到++a(前置++),就调用operator++(a),当编译器看到a++(后置++),就会调用operator++(a,int)
#include <iostream>
using namespace std;
class Data
{
friend ostream& operator<<(ostream &out,Data &ob);
private:
int a;
int b;
public:
Data()
{
cout << "无参的构造函数" << endl;
a = 0;
b = 0;
}
Data(int a, int b):a(a),b(b)
{
cout << "有参构造函数" << endl;
}
void showData(void)
{
cout << "a = " << a << " b = " << b << endl;
}
//++ob1
//编译器默认识别operator++(a),但是a可以用this代替,从而化简
Data& operator++()
{
a++;
b++;
return *this;
}
//ob1++
Data& operator++(int)
{
static Data tmp_data = *this;
a++;
b++;
return tmp_data;
}
Data& operator--()
{
a--;
b--;
return *this;
}
Data& operator--(int)
{
static Data tmp_data = *this;
a--;
b--;
return tmp_data;
}
~Data()
{
cout << "析构函数" << endl;
}
};
ostream& operator<<(ostream &out,Data &ob)
{
out << "a = " << ob.a << " b = " << ob.b << endl;
return out;
}
int main()
{
Data ob1(10,20);
ob1.showData();
cout << ++ob1;
Data ob2(15,25);
cout << ob2++;
cout << ob2;
Data ob3(20,30);
cout << --ob3;
Data ob4(25,35);
cout << ob4--;
cout << ob4;
return 0;
}
知识点3 重载指针运算符*->实现智能指针
#include <iostream>
using namespace std;
class Person
{
private:
int num;
public:
Person(int num):num(num)
{
cout << "有参构造" << endl;
}
void showPerson(void)
{
cout << "num = " << num << endl;
}
~Person()
{
cout << "析构函数" << endl;
}
};
//设计一个智能指针解决堆区空间的释放问题
class SmartPointer
{
public:
Person *pPerson;
public:
SmartPointer(Person *p)
{
pPerson = p;
}
~SmartPointer()
{
if (pPerson != NULL)
{
delete pPerson;
pPerson = NULL;
}
}
//重载->运算符
Person* operator->()
{
return this->pPerson;
}
//重载*运算
Person& operator*()
{
return *(this->pPerson);
}
};
int main()
{
Person *p = new Person(100);
p->showPerson();
//需要手动写delete p才能够释放空间,容易造成内存泄漏
delete p;
//使用智能指针
SmartPointer pointer(new Person(200));
//访问person类中的方法
//pointer.pPerson->showPerson();
//(pointer.operator -> ())->showPerson();
pointer->showPerson();
(*pointer).showPerson();
return 0;
}