c++從入門到精通——運算符重載(三)指針運算符重載和類成員訪問運算符

指針運算符重載

類成員訪問運算符 -> 重載

類成員訪問運算符( -> )可以被重載,但它較爲麻煩。它被定義用於爲一個類賦予"指針"行爲。運算符 -> 必須是一個成員函數。如果使用了 -> 運算符,返回類型必須是指針或者是類的對象。

運算符 -> 通常與指針引用運算符 * 結合使用,用於實現"智能指針"的功能。這些指針是行爲與正常指針相似的對象,唯一不同的是,當您通過指針訪問對象時,它們會執行其他的任務。比如,當指針銷燬時,或者當指針指向另一個對象時,會自動刪除對象。

例子 智能指針

#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;
}

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章