定义:在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。this 指针是所有成员函数的隐含参数。因此,在成员函数内部,它可以用来指向调用对象。
this只能在成员函数中使用
成员函数默认第一个参数为T* const register this。
(友元函数,全局函数不是成员函数)
this指针不能再静态函数中使用
静态函数如同静态变量一样,他不属于具体的哪一个对象,静态函数表示了整个类范围意义上的信息,而this指针却实实在在的对应一个对象,所以this指针不能被静态函数使用。
this指针的创建
this指针在成员函数的开始执行前构造的,在成员的执行结束后清除。
this指针只有在成员函数中才有定义。
创建一个对象后,不能通过对象使用this指针。也无法知道一个对象的this指针的位置(只有在成员函数里才有this指针的位置)。当然,在成员函数里,你是可以知道this指针的位置的(可以&this获得),也可以直接使用的。
编译器针对程序员自己设计的类型分三次编译。
第一:识别和记录类体中属性的名称,类型和访问限定,与属性在类体中的位置无关。
如:class CGoods中的Name,Amount,Price,Total_value;
第二:识别和记录类体中的函数原型(返回类型+函数名+参数列表),形参的默认值,访问限定。不识别体函数。
第三:改写在类中定义的参数列表和函数体,改写对象调用成员函数的形式。
示例:
#includeusing namespace std; class CGoods { private: char Name[21]; int Amount; float Price; float Total_value; public: void registerGoods(char[], int, float); //输入数据 void countTotal(); //计算商品的总价 }; //最后的分号不可少 void CGoods::registerGoods(char name[], int amount, float price) { strcpy_s(Name, name); Amount = amount; Price = price; } void CGoods::countTotal() { Total_value = Price * Amount; } int main() { CGoods tea; CGoods book; tea.registerGoods("black_tea", 12, 560); tea.countTotal(); book.registerGoods("C++", 20, 128); book.countTotal(); return 0; }
用this改写后的代码:
#includeusing namespace std; class CGoods { private: char Name[21]; int Amount; float Price; float Total_value; public: //void registerGoods(CGoods * const this,char[], int, float); void registerGoods(char[], int, float); //输入数据 //void countTotal(CGoods * const this); void countTotal(); //计算商品的总价 }; //最后的分号不可少 //void CGoods::registerGoods(CGoods * const this,char name[], int amount, float price) void CGoods::registerGoods(char name[], int amount, float price) { strcpy_s(this->Name, name); this->Amount = amount; this->Price = price; } //void CGoods::countTotal(CGoods * const this) void CGoods::countTotal() { this->Total_value = this->Price * this->Amount; } int main() { CGoods tea; CGoods book; tea.registerGoods("black_tea", 12, 560); //registerGoods(&tea,"black_tea", 12, 560); tea.countTotal(); //countTotal(&tea) book.registerGoods("C++", 20, 128); // registerGoods(&book,"C++", 20, 128); book.countTotal(); //countTotal(&book); return 0; }
关于this指针的一个精典回答:
三. this指针的特点 :当你进入一个房子后,
你可以看见桌子、椅子、地板等,
但是房子你是看不到全貌了。
对于一个类的实例来说,
你可以看到它的成员函数、成员变量,
但是实例本身呢?
this是一个指针,
它时时刻刻指向你这个实例本身。
在C++中,类中的成员函数和成员变量是分开存储的,特点如下:
1.非静态成员变量属于类的对象上;
2.静态成员变量由所有对象共享;
3.非静态成员函数和静态成员函数都由所有对象所共享。
综上所述,只有非静态成员变量才属于类的对象上。
那么问题来了,类的非静态成员函数是如何区分是哪个对象在调用自己呢?这就需要用到this指针。this指针有如下特点:
1.指向当前调用成员函数的对象;
2.是一个指针常量,即确定指向后不能随意修改指向。
3.this指针是隐含每一个非静态成员函数内的一种指针;
4.this指针不需要定义,直接使用即可。



