在构造一个对象时,默认会生成一个指向当前对象的指针,这个的目的就是为了带来方便,它就是this指针,举例几个常见this指针的用途。
第一种:若成员函数中传递进来的参数与成员变量名字相等,那么赋值时就会出现问题。如下:
class CStudent { public: CStudent(string name, int age) { // 想将形参中name赋值给成员变量name name = name; // 想将形参中age赋值给成员变量age age = age; } ~CStudent(); private: string name; int age; };
使用this指针就可以解决这个问题,如下:
class CStutent { public: CStutent(string name, int age) { // this == &CStudent this->name = name; this->age = age; } ~CStutent(); private: string name; int age; };
第二种:可以给让某成员函数返回this指针所指向的自身对象,这样就可以在一个语句中连续调用成员方法了(多重串联调用)。如下所示:
#include <iostream> #include <string> using namespace std; class CStudent { public: CStudent(string name, int age) { this->name = name; this->age = age; } CStudent& growUp() { age++; // 返回 *this 是将整个对象返回 // 可以让main函数中调用growUp方法后继续调用growUp return *this; } void display() { cout << "name:" << name << endl << "age:" << age << endl; } ~CStudent(){} private: string name; int age; }; int main(int argc, char* argv[]) { CStudent s("dengjia", 25); // growUp后返回的是CStudent对象,所以可以继续调用其growUp方法 s.growUp().growUp().growUp(); s.display(); getchar(); return 0; }