86.指针运算符重载

智能指针实现
    Person类有showAge 成员函数
    如果new出来的Person对象,就要让程序员自觉的去释放  delete
    有了智能指针,让智能指针托管这个Person对象,对象的释放就不用操心了,让智能指针管理
    为了让智能指针想普通的Person*指针一样使用 就要重载 -> 和*

// 53.指针运算符重载.cpp : 定义控制台应用程序的入口点。
//

#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的析构调用" << 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); //自动析构

	//Person * p1 = new Person(10);
	//p1->showAge();
	//	delete p1;


	smartPointer sp(new Person(10)); //sp开辟到了栈上,自动释放
	sp->showAge(); // sp->->showAge(); 编译器优化了 写法

	(*sp).showAge();
	/*输出
	年龄为:10
	年龄为:10
	智能指针析构了
	Person的析构调用
	*/
}


int main(){

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值