C++ this指针
在C++编程中, this 是一个关键字,用于引用当前类的实例。在C++中,this关键字有三种主要的用法。
- 它可以被用来将当前对象作为参数传递给另一个方法。
 - 它可以被用来引用当前类的实例变量。
 - 它可以被用来声明索引器。
 
C++ this指针示例
让我们来看一个C++中使用this关键字引用当前类字段的例子。
#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, "Sonoo", 890000); //creating an object of Employee 
    Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
    e1.display();  
    e2.display();  
    return 0;
}
输出:
101  Sonoo  890000
102  Nakul  59000
极客笔记