成员变量和成员函数分开存储
C++中类的成员变量和成员函数分开存储,只有非静态成员变量才属于类的对象上。
this指针
this指针指向被调用的成员函数所属的对象。
不需定义,直接调用。
用途:
1,形参和成员变量同名时,用this指针来区分
2,在类的非静态成员函数中返回对象本身,可使用return *this
class person
{
public:
int age;
person(int age)
{
//this指针指向被调用的成员函数所属的对象
this->age = age;
}
person& personaddage(person& p)
{
this->age += p.age;
//this是指向p2的指针,而*this是指向p2这个对象的本身
return *this;
}
};
void test02()
{
person p1(10);
person p2(10);
p2.personaddage(p1).personaddage(p1);
cout << "age of p=" << p2.age << endl;
}
int main()
{
test02();
return 0;
}