C++复习8
C++ this指針詳解
this 是C++中的一個關鍵字,也是一個常量指針,指向當前對象(具體說是當前對象的首地址)。通過 this,可以訪問當前對象的成員變量和成員函數。所謂當前對象,就是正在使用的對象,例如對于stu.say();,stu 就是當前對象,系統正在訪問 stu 的成員函數 say()。
假設 this 指向 stu 對象,那么下面的語句中,this 就和 pStu 的值相同:
Student stu; //通過Student類來創建對象
Student *pStu = &stu;
[示例] 通過 this 來訪問成員變量:
class Student{
private:
char *name;
int age;
float score;
public:
void setname(char *);
void setage(int);
void setscore(float);
};
void Student::setname(char *name){
this->name = name;
}
void Student::setage(int age){
this->age = age;
}
void Student::setscore(float score){
this->score = score;
}
本例中,函數參數和成員變量重 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結