#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
cout << "Person的有参构造调用" << endl;
this->m_Age = age;
}
void showAge()
{
cout << "年龄为 "<< this->m_Age << endl;
}
~Person()
{
cout << "Person的析构调用" << endl;
}
int m_Age;
};
class SmartPoint
{
public:
SmartPoint(Person * person)
{
this->m_person = person;
}
//重载->运算符
Person * operator->()
{
return this->m_person;
}
//重载 * 运算符
Person& operator*()
{
return *m_person;
}
~SmartPoint()
{
if (this->m_person)
{
delete this->m_person;
this->m_person = NULL;
}
}
//sp开辟到栈上,就一定会有析构
//new出来的对象一定会调用它的析构代码
private:
Person * m_person;
};
void test01()
{
//Person * p = new Person(18);
//指针调用对象两种方法
//(*p).showAge();
//p->showAge();
//delete p;
//利用只能指针 管理 new出来的person的释放操作
SmartPoint sp(new Person(18));
sp->showAge(); // 本质sp->->showAge(); 编译器简化为 sp->showAge();
(*sp).showAge();
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
肆-拾陆|指针运算符重载
最新推荐文章于 2024-06-15 22:21:25 发布