C++智能指針簡單案例

智能指針其實就是對->和*運算符重載的應用

#include <iostream>
#include <cstring>
using namespace std;

class Person{
public:
	Person(int age){
		cout << "有參構造函數調用" << endl;
		this->m_age = age;
	}
	void showAge(){
		cout << "年齡:" << this->m_age << endl;
	}
	~Person(){
		cout << "析構函數調用" << endl;
	}
private:
	int m_age;
};

//智能指針 用來託管new出來的對象的釋放
class SmartPointer{
public:
	SmartPointer(Person* person){
		cout << "SmartPointer" << endl;
		this->person = person;
	}
	
	//重載指針運算符
	Person* operator->(){
		return this->person;
	}
	
	//重載*運算符
	Person& operator*(){
		return *this->person;
	}
	
	~SmartPointer(){
		if(this->person != NULL){
			cout << "~SmartPointer" << endl;
			delete this->person;
			this->person = NULL;
		}
	}
private:
	Person* person;
};
void test01(void){
	// Person* p = new Person(18); 
	// delete p;
	SmartPointer sp = SmartPointer(new Person(18));
	sp->showAge(); //sp->->showAge(),編譯器簡化爲sp->showAge()
	(*sp).showAge();
}
int main(int argc, char* argv[]){
	test01();
	system("pause");
	return 0;
}
發佈了120 篇原創文章 · 獲贊 73 · 訪問量 42萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章