this指针
this指针指向被调用的成员函数所属的对象
this指针的用途:
当形参和成员变量同名时,可用this指针来区分
class animal{
pubilc:
animal(int age){//把传进来的age赋值给成员变量age
this->age = age;//this->age指成员变量age
}
public:
int age;
}
在类的非静态成员函数中返回对象本身,可使用return *this
class animal{
pubilc:
animal(int age){//把传进来的age赋值给成员变量age
this->age = age;//this->age指成员变量age
}
animal& fun(animal p)
{
this->age += p.age;//加上传进来对象的age
return *this;//返回对象本身
}
public:
int age;
}
int main(){
animal p1;
animal p2;
p2.fun(p1).fun(p1).fun(p1);
//相当于调用了3次p2.fun(p1);
}