C++中的this指標
阿新 • • 發佈:2022-04-18
概念:this實際上是成員函式得一個形參,在呼叫成員函式時將物件的地址作為實參傳遞給this。this這個形參是隱式的,並不會出現在程式碼中,而是在編譯階段由編譯器隱式地將其新增至引數列表中。
this使用的基本原則:若程式碼不存在二義性隱患,就不必使用this指標
class Human { public: void setName(char *name); void setAge(int age); void show(); private: char *name; int age; };void Human::setName(char *name) { this->name = name; } void Human::setAge(int age) { this->age = age; } void Human::show() { cout << this->name << "的年齡是" << this->age << endl; } void main() { Human *zjm=new Human; zjm->setName("小明"); zjm->setAge(18); zjm->show(); system("pause"); return; }
this只能用在類的內部(因為this本質上是成員函式的區域性變數),通過this可以訪問類內的所有成員(包含private、protected)
成員函式的引數與成員變數重名時,要用this進行區分。
注意:this是一個指標,要用->來訪問成員變數或成員函式