本文共 2453 字,大约阅读时间需要 8 分钟。
转载自:http://c.biancheng.net/cpp/biancheng/view/201.html
this 是C++中的一个关键字,也是一个常量指针,指向当前对象(具体说是当前对象的首地址)。通过 this,可以访问当前对象的成员变量和成员函数。
所谓当前对象,就是正在使用的对象,例如对于 stu.say();
,stu 就是当前对象,系统正在访问 stu 的成员函数 say()。
假设 this 指向 stu 对象,那么下面的语句中,this 就和 pStu 的值相同: Student stu; //通过Student类来创建对象 Student *pStu = &stu;
class Student{ private: char *name; int age; float score; public: void setname(char *); void setage(int); void setscore(float); }; void Student::setname(char *name){ this->name = name; } void Student::setage(int age){ this->age = age; } void Student::setscore(float score){ this->score = score; }
this->name = name;
语句,赋值号左边是类的成员变量,右边是 setname 函数的局部变量,也就是参数。 下面是一个完整的例子: #includeusing namespace std; class Student{ private: char *name; int age; float score; public: void setname(char *); void setage(int); void setscore(float); void say(); }; 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::say(){ cout< name<<"的年龄是 "< age<<",成绩是 "< score<
void Student::printThis(){ cout<<
Student stu1, *pStu1 = &stu1; stu1.printThis(); cout<<