在C++编程中, this 是一个关键字,它引用该类的当前实例。在C++中,此关键字的3种主要用法。
让我们看一下C++中此关键字的示例,该示例引用当前类的字段。
#include <iostream> using namespace std; class Employee { public: int id; //数据成员(也是实例变量) string name; 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); //创建 Employee 对象 Employee e2=Employee(102, "Nakul", 59000); //创建 Employee 对象 e1.display(); e2.display(); return 0; }
输出:
101 Sonoo 890000 102 Nakul 59000
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)