C++ this指針

在C++編程中,this是一個引用類的當前實例的關鍵字。 this關鍵字在C++中可以有3個主要用途。

  1. 用於將當前對象作為參數傳遞給另一個方法。
  2. 用來引用當前類的實例變數。
  3. 用來聲明索引器。

C++ this指針的例子

下麵來看看看this關鍵字在C++中的例子,它指的是當前類的字段。

#include <iostream>
using namespace std;
class Employee {
   public:
       int id; //data member (also instance variable)
       string name; //data member(also instance variable)
       float salary;
       Employee(int id, string name, float salary)
        {
             this->id = id;
            this->name = name;
            this->salary = salary;
        }
       void display()
        {
            cout<<id<<"  "<<name<<"  "<<salary<<endl;
        }
};
int main(void) {
    Employee e1 =Employee(101, "Hema", 890000); //creating an object of Employee
    Employee e2=Employee(102, "Calf", 59000); //creating an object of Employee
    e1.display();
    e2.display();
    return 0;
}

輸出結果如下 -

101  Hema  890000
102  Calf  59000

上一篇: C++對象和類 下一篇: C++ static關鍵字