5.1 指针永远指向当前对象
5.2 解决命名冲突
5.3 *this 指向对象本体
5.4 非静态的成员函数才有this指针
#include<iostream>
#include<string>
using namespace std;
class Student {
public:
Student(int age) {
this->age = age;
}
//对比年龄
void compareAge(Student &st) {
if (this->age == st.age) {
cout << "年龄相等" << endl;
}
else {
cout << "年龄不相等" << endl;
}
}
//年龄相加
Student & plusAge(Student &st) {
this->age += st.age;
return *this; //*this指向对象本体
}
int age;
};
void test01() {
Student st1(7);
cout << "st1的年龄" << st1.age << endl;
Student st2(7);
st1.compareAge(st2);
st1.plusAge(st2).plusAge(st2); //链式编程
cout << "st1的年龄" << st1.age << endl;
}
int main(){
test01();
system("pause");
return 0;
}