指针运算符重载
类成员访问运算符 -> 重载
类成员访问运算符( -> )可以被重载,但它较为麻烦。它被定义用于为一个类赋予"指针"行为。运算符 -> 必须是一个成员函数。如果使用了 -> 运算符,返回类型必须是指针或者是类的对象。
运算符 -> 通常与指针引用运算符 * 结合使用,用于实现"智能指针"的功能。这些指针是行为与正常指针相似的对象,唯一不同的是,当您通过指针访问对象时,它们会执行其他的任务。比如,当指针销毁时,或者当指针指向另一个对象时,会自动删除对象。
例子 智能指针
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
this->m_Age = age;
}
void showAge()
{
cout << "年龄为:" << this->m_Age << endl;
}
~Person()
{
cout << "Person的析构调用" << "(年龄为:" << this->m_Age<<")" << endl;
}
int m_Age;
};
//智能指针
//用来托管自定义类型的对象,让对象进行自动的释放
class smartPointer
{
public:
smartPointer(Person * person)
{
this->person = person;
}
//重载->让智能指针对象 想Person *p一样去使用
Person * operator->()
{
return this->person;
}
//重载 *
Person& operator*()
{
return *this->person;
}
~smartPointer()
{
cout << "智能指针析构了" << endl;
if (this->person !=NULL)
{
delete this->person;
this->person = NULL;
}
}
private:
Person * person;
};
void test01()
{
Person p1(10); //自动析构
p1.showAge();
Person * p2 = new Person(20);
p2->showAge();
delete p2;
}
void test02()
{
smartPointer sp(new Person(10)); //sp开辟到了栈上,自动释放
sp->showAge(); // sp->->showAge(); 编译器优化了 写法
(*sp).showAge();
}
int main(){
//test01();
test02();
system("pause");
return EXIT_SUCCESS;
}