c++ 關鍵字this的用法簡介


前言:

自己在程序的時候一般不用this,但是在后來發現越來越有必要好好整理一下該知識點了,如有不足之處以及缺漏之處還望各位讀者指出。

概念&實例

this 是 C++ 中的一個關鍵字,也是一個 const 指針,它指向當前對象,通過它可以訪問當前對象的所有成員。所謂當前對象,是指正在使用的對象。this 只能用在類的內部,通過 this 可以訪問類的所有成員,包括 private、protected、public 屬性的。

#include <iostream>
using namespace std;

class Student{
public:
    void setname(char *name);
    void setage(int age);
    void setscore(float score);
    void show();
private:
    char *name;
    int age;
    float score;
};

void Student::setname(char *name){
    this->name = name;
}
void Student::setage(int age){
    this->age = age;
}
void Student::setscore(float score){
    this->score = score;
}
void Student::show(){
    cout<<this->name<<"的年齡是"<<this->age<<",成績是"<<this->score<<endl;
}

int main(){
    Student *pstu = new Student; 
    pstu -> setname("李華");
    pstu -> setage(16);
    pstu -> setscore(96.5);
    pstu -> show();

    return 0;
}

本例中成員函數的參數和成員變量重名,只能通過 this 區分。以成員函數setname(char *name)為例,它的形參是name,和成員變量name重名,如果寫作name = name;這樣的語句,就是給形參name賦值,而不是給成員變量name賦值。而寫作this -> name = name;后,=左邊的name就是成員變量,右邊的name就是形參,一目了然。需要注意的是:this 是一個指針,要用->來訪問成員變量或成員函數。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM