c++ (运算符重载 && 智能指针)

c++ (运算符重载 && 智能指针)

class Person
{
public:
	Person(){}
	Person(int age):m_Age(age){}
	void showAge()
	{
		cout << "年龄为: " << this->m_Age;
	}
	int m_Age;
	~Person()
	{
		cout << "析构调用了" << endl;
	}
};

//智能指针
//用来托管自定义类型的对象,让对象进行自动的释放
class smartPointer
{
public:
	smartPointer(Person * person) {
		this->person = person;
	}
	~smartPointer()
	{
		cout << "智能指针析构了" << endl;
		if (this->person != NULL) {
			delete this->person;
			this->person = NULL;
		}
	}
	//重载->让只能指针对象,像Person *p一样去使用
	Person* operator->()
	{
		return this->person;
	}
	Person& operator*()
	{
		return *this->person;
	}
private:
	Person * person;

};

void  text01()
{
	smartPointer sp(new Person(10)); //开辟到了栈上,会自动释放
	sp->showAge();
	(*sp).showAge();
}

posted on 2021-04-23 17:05  lodger47  阅读(112)  评论(0)    收藏  举报

导航