this指针
this指针
-
this指针指向被调用的成员函数所属的对象。
-
含义:
1、this指针是隐含每一个非静态成员函数内的一种指针。
2、this指针不需要定义,直接使用即可。 -
用途:
1、当形参和成员变量同名时,可用this指针来区分。
2、在类的非静态成员函数中返回对象本身,可使用return *this。
#include <iostream>
#include <string>
using namespace std;
class person{
public:
person(int age){//当形参和成员变量同名时,可以用this指针来区分(用途1)。
this->age = age;
}
person& personaddage(person &p){
this->age += p.age;
return *this;//this是指向p2的指针,*this就是p2这个对象本体(用途2)。
}//返回对象本体(p2)。
int age;
};
void test1(){
person p(18);
cout << p.age << endl;
}
void test2(){
person p1(10);
person p2(10);//链式编程思想
p2.personaddage(p1).personaddage(p1).personaddage(p1);
cout << "p2的年龄为:" << p2.age << endl;
}
int main(void)
{
// test1();
test2();
return 0;
}
空指针访问成员函数中this指针的问题
空指针也可以访问成员函数,如果加上this指针后报错则加上以下几行代码
if(this == NULL){
return;
}