C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ this指针

在C++编程中, this是引用该类当前实例的关键字。在C++中,this关键字的主要用法有3种。
可以使用它将当前对象作为参数传递给另一种方法。 可用于引用当前类实例变量。 可用于声明索引器。

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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4