在面向对象程序设计中,每个非静态成员函数中都包含一个特殊的指针,指向调用该函数的对象,这个称为this指针。当对象访问类中的非静态成员函数时,编译器会自动将对象的地址隐式地作为第一个参数传递给this指针,在非静态成员函数中访问非静态成员时都隐含地使用了this指针。
class Student{
private:
int age;
public:
void setAge(int age){this->age = age;}
int getAge(){return age;}
};
int main(){
Student stud = Student();
stud.setAge(20);
cout<<stud.getAge()<<endl;
getchar();
}
this指针的作用域是在非静态成员函数内部,在调用非静态成员函数时构造this指针,在非静态成员函数调用结束后销毁this指针。
通过this指针访问的数据成员和方法成员都必须是类的非静态成员。类的非静态成员属于整个类,不属于某一个对象,没有对象也就谈不上this指针,因此this指针只能在类的非静态成员函数中出现,而不能在类的静态成员函数中使用。
在代码编写过程中,有时也会显式地使用this指针。当参数名与对象数据成员的名称冲突时,必须通过使用this指针加以区分。
当函数需要返回对象的地址时,可以返回this指针。因为this指针指向对象,可以通过this指针直接得到对象的地址。
Student* setAge(int age) {this->age = age; return this;}
Student* setName(string name) {this->name = name; return this;}
Student* setGender(char gender) {this->gender = gender; return this;}
将对象的地址作为返回值主要是为了支持链式访问。
Student *pstud = new Student();
pstud->setName("Tom")->setAge(10)->setGender("M");