this指针的用途:
- 当形参和成员变量同名时,可用this指针来区分
- 在类的非静态成员函数中返回对象本身,可使用return *this;
当我们再编写代码的时候,可能会遇到这样的问题:
class Person { public: Person(int age) { age = age; } int age; }; void test01() { Person p1(18); cout << "p1的年龄为:" << p1.age << endl; } int main() { test01; return 0; }
为什么输出的年龄不是18呢?原因是再Person的构造函数中,前后两个age是同一个变量。要想解决这个问题,有两种方法,一种是将Person类属性中的age变量名修改例如修改成m_age,避免变量名引起冲突。第二种就是要用到我们今天所要讲的内容——this指针 了
class Person { public: Person(int age) { this->age = age; } int age; }; void test01() { Person p1(18); cout << "p1的年龄为:" << p1.age << endl; } int main() { test01(); return 0; }
这是我们输出的结果就正确了
当然 ,this指针也可以指向被调用的成员函数所属的对象
class Person { public: Person(int age) { this->age = age; } void PersonAddAge(Person& p) { this->age += p.age; } int age; }; void test02() { Person p1(10); Person p2(10); p2.PersonAddAge(p1); cout << "p2的年龄为:" << p2.age << endl; } int main() { test02(); return 0; }
此时输出的结果是将p1和p2的年龄相加:
this指针还可以使用在链式编程中,需要将上述代码中的PersonAddAge函数稍作修改:
class Person { public: Person(int age) { this->age = age; } Person& PersonAddAge(Person& p) { this->age += p.age; //this指向p2的指针,而*this指向的就是p2这个对象本体 return *this; } int age; }; void test02() { Person p1(10); Person p2(10); p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1); cout << "p2的年龄为:" << p2.age << endl; } int main() { test02(); return 0; }
此时输出的是p2的年龄和4个p1的年龄相加:
注意:PersonAddAge函数前必须加上“&”,表示以引用的形式进行传递。如果是值传递,返回的并不是p2的本体,而是用p2的本体创建出一份新的数据。