1.问题:每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会共用一块代码,这一块代码是如何区分哪个对象调用自己的呢?
2.解决方法:C++会提供特殊的对象指针,this指针,解决上述的问题,this指针指向被调用的成员函数所属的对象
3.要点:(1)this指针是隐含每一个非静态成员函数内的一种指针
(2)this指针不需要定义直接使用即可
4.this指针的用途:
(1)在形参和成员变量同名时,可用this指针来区分->解决对象冲突
(2)在类的非静态成员函数中返回对象本身,可使用return*this->返回对象本身;
(1)用途一的体现,仔细比较Person 和Person1的不同点
class Person {
public:
Person(int age) {
this->age = age;
}
int age;
};
class Person1 {
public:
Person1(int age1) {
age1 = age;
}
int age;
};
void test01() {
Person p1(18);
Person p2(19);
cout << p1.age << endl;
cout << p2.age << endl;
}
int main() {
test01();
}
(2)用途二的体现
#include<iostream>
using namespace std;
class Person {
public:
Person(int age) {
this->age = age;
}
Person& PersonAddPerson(Person&p) {
this->age += p.age;//将另一个年龄与自身的年龄相加
return*this;//this指向p2的指针,而*this指向的就是p2这个对象的本体
//而返回其本体需要用引用的方式返回
}
int age;
};
void test01() {
Person p1(18);
cout << p1.age << endl;
}
void test02() {
Person p1(10);
cout << "p1的年龄为:" << p1.age << endl;
Person p2(10);
cout << "p2原来的年龄为:" << p2.age << endl;
p2.PersonAddPerson(p1);
cout << "p2相加后的年龄为:" << p2.age << endl;
//链式编程的思想
p2.PersonAddPerson(p1).PersonAddPerson(p2);
cout << "p2多次相加后的年龄为:" << p2.age << endl;
}
int main() {
test01();
test02();
}
输出:p2多次相加后的结果输出为60也是我们想要得出的结果
问题:为什么返回的必须是Person&//即用引用的方式返回
现在将代码改为不使用引用的方式返回
#include<iostream>
using namespace std;
class Person {
public:
Person(int age) {
this->age = age;
}
Person PersonAddPerson(Person&p) {
this->age += p.age;//将另一个年龄与自身的年龄相加
return*this;//this指向p2的指针,而*this指向的就是p2这个对象的本体
//而返回其本体需要用引用的方式返回
}
int age;
};
void test01() {
Person p1(18);
cout << p1.age << endl;
}
void test02() {
Person p1(10);
cout << "p1的年龄为:" << p1.age << endl;
Person p2(10);
cout << "p2原来的年龄为:" << p2.age << endl;
p2.PersonAddPerson(p1);
cout << "p2相加后的年龄为:" << p2.age << endl;
//链式编程的思想
p2.PersonAddPerson(p1).PersonAddPerson(p1).PersonAddPerson(p2);
cout << "p2多次相加后的年龄为:" << p2.age << endl;
}
int main() {
test01();
test02();
}
输出:p2多次相加后输出的结果为30//即并非是我们想要的出的那个结果
原因:返回为Person而不是Person&时,返回的就不是其本身,每一次返回都是一个新的对象