跳到正文

Wiki

對象模型與this指針

約 2 分鐘閱讀

本文由簡體中文內容確定性轉換,並受版本化術語表保護。

1.C++對象模型和this指針

1.1.成員變量和成員函數分開存儲

在C++中,類內的成員變量和成員函數分開存儲

只有非靜態成員變量才屬於類的對象上

class Person {
public:
	Person() {
		mA = 0;
	}
	//非静态成员变量占对象空间
	int mA;
	//静态成员变量不占对象空间
	static int mB; 
	//函数也不占对象空间,所有函数共享一个函数实例
	void func() {
		cout << "mA:" << this->mA << endl;
	}
	//静态成员函数也不占对象空间
	static void sfunc() {
	}
};

int main() {

	cout << sizeof(Person) << endl;


	return 0;
}

運行結果(類型大小或類型名可能隨編譯器和平台變化):

4

1.2.this指針概念

通過4.3.1我們知道在C++中成員變量和成員函數是分開存儲的

每一個非靜態成員函數只會誕生一份函數實例,也就是説多個同類型的對象會共用一塊代碼

那麼問題是:這一塊代碼是如何區分那個對象調用自己的呢?

c++通過提供特殊的對象指針,this指針,解決上述問題。this指針指向被調用的成員函數所屬的對象

this指針是隱含每一個非靜態成員函數內的一種指針

this指針不需要定義,直接使用即可

this指針的用途:

  • 當形參和成員變量同名時,可用this指針來區分
  • 在類的非靜態成員函數中返回對象本身,可使用return *this
class Person
{
public:

	Person(int age)
	{
		//1、当形参和成员变量同名时,可用this指针来区分
		this->age = age;
	}

	Person& PersonAddPerson(Person p)
	{
		this->age += p.age;
		//返回对象本身
		return *this;
	}

	int age;
};

void test01()
{
	Person p1(10);
	cout << "p1.age = " << p1.age << endl;

	Person p2(10);
	p2.PersonAddPerson(p1).PersonAddPerson(p1).PersonAddPerson(p1);
	cout << "p2.age = " << p2.age << endl;
}

int main() {

	test01();


	return 0;
}

運行結果:

p1.age = 10
p2.age = 40

1.3.空指針訪問成員函數

C++中空指針也是可以調用成員函數的,但是也要注意有沒有用到this指針

如果用到this指針,需要加以判斷保證代碼的健壯性

示例:

//空指针访问成员函数
class Person {
public:

	void ShowClassName() {
		cout << "我是Person类!" << endl;
	}

	void ShowPerson() {
		if (this == NULL) {
			return;
		}
		cout << mAge << endl;
	}

public:
	int mAge;
};

void test01()
{
	Person * p = NULL;
	p->ShowClassName(); //空指针,可以调用成员函数
	p->ShowPerson();  //但是如果成员函数中用到了this指针,就不可以了
}

int main() {

	test01();


	return 0;
}

運行結果:

我是Person类!

1.4.const修飾成員函數

常函數:

  • 成員函數後加const後我們稱為這個函數為常函數
  • 常函數內不可以修改成員屬性
  • 成員屬性聲明時加關鍵字mutable後,在常函數中依然可以修改

常對象:

  • 聲明對象前加const稱該對象為常對象
  • 常對象只能調用常函數

示例:

class Person {
public:
	Person() {
		m_A = 0;
		m_B = 0;
	}

	//this指针的本质是一个指针常量,指针的指向不可修改
	//如果想让指针指向的值也不可以修改,需要声明常函数
	void ShowPerson() const {
		//const Type* const pointer;
		//this = NULL; //不能修改指针的指向 Person* const this;
		//this->mA = 100; //但是this指针指向的对象的数据是可以修改的

		//const修饰成员函数,表示指针指向的内存空间的数据不能修改,除了mutable修饰的变量
		this->m_B = 100;
	}

	void MyFunc() const {
		//mA = 10000;
	}

public:
	int m_A;
	mutable int m_B; //可修改 可变的
};

//const修饰对象  常对象
void test01() {

	const Person person; //常量对象  
	cout << person.m_A << endl;
	//person.mA = 100; //常对象不能修改成员变量的值,但是可以访问
	person.m_B = 100; //但是常对象可以修改mutable修饰成员变量

	//常对象访问成员函数
	person.MyFunc(); //常对象不能调用const的函数

}

int main() {

	test01();


	return 0;
}

運行結果:

0