class Person
{
public:int m_A;//非靜態成員變量,屬于對象上void func(/*Person * this*/){}; //非靜態成員函數 不屬于對象身上static int m_B;//靜態成員函數,不屬于對象上static void fun2(){};//靜態成員函數 ,不屬于對象身上//double m_C;//12錯誤 16正確,解決方法#pragma pack(1)
};
void test02()
{//this指針指向被調用的成員函數Person p1;p1.func(); //編譯器會偷偷 加入一個this指針 Person * this Person p2;p2.func();
}
C++編譯器給每個“成員函數“增加了一個隱藏的指針參數,讓該指 針指向當前對象(函數運行時調用該函數的對象),在函數體中所有成員變量的操作,都是通過該指針去訪 問。只不過所有的操作對用戶是透明的,即用戶不需要來傳遞,編譯器自動完成。
this指針使用
- 指針永遠指向當前對象
- 解決命名沖突
- *this指向對象的本體
- 非靜態成員函數才有this指針
this指針的類型:
-
類類型* const
-
只能在“成員函數”的內部使用
-
this指針本質上其實是一個成員函數的形參,是對象調用成員函數時,將對象地址作為實參傳遞給this 形參。所以對象中不存儲this指針。
-
this指針是成員函數第一個隱含的指針形參,一般情況由編譯器通過ecx寄存器自動傳遞,不需要用戶 傳遞
#include<iostream>using namespace std;// this 可以解決命名沖突class Person{public:Person(int age){this->age = age;}//對比年齡void compareAge(Person &p){if (this->age == p.age){cout << "相等" << endl;}else{cout << "不相等" << endl;}}//年齡相加Person& PlusAge(Person &p){this->age += age;return *this; //*this指向對象的本體}int age;};void test01(){Person p1(10);cout << "p1的年齡" << p1.age << endl;Person p2(10);p1.compareAge(p2);p1.PlusAge(p2).PlusAge(p2);//鏈式編程//函數返回值作為左值 返回引用cout << "p1的年齡" << p1.age << endl;}int main(){test01();system("pause");return 0;}