C++ this指针作用解析

tech2022-10-10  87

this指针用途:

当形参和成员变量同名时,可用this指针来区分在类的非静态成员函数中返回对象本身,可使用return *this #include <iostream> using namespace std; class Person { public: int age; Person(int age) { this->age=age; //1.当形参和成员变量同名时,可用this指针来区分 } Person & AddAge(Person &p1) //更改本体,需要引用返回本体 { this->age+=p1.age; return *this; //2.在类的非静态成员函数中返回对象本身,可使用return *this } }; void func1() { Person p1(18); cout<<p1.age<<endl; } void func2() { Person p1(10); Person p2(10); p2.AddAge(p1).AddAge(p1).AddAge(p1); //链式编程思想 cout<<p2.age<<endl; } int main() { func1(); func2(); return 0; }

最新回复(0)