1 this指针简介
关于this指针有如下几点需要注意:
- 在类的静态成员函数中,不能使用this指针!
- this不能指向其他对象,堪称“永不迷失的真爱”。
2 this指针的常用用法
2.1 用于访问类的成员
Human::Human(int age, int salary) {
cout << "调用自定义的构造函数" << endl;
this->age = age; //this是一个特殊的指针,指向这个对象本身
this->salary = salary;
name = "无名";
addr = new char[64];
strcpy_s(addr, 64, "China");
}
2.2 返回当前对象的指针
const Human* Human::compare1(const Human * other) {
if (age > other->age) {
return this; //没有创建新的对象
}
else {
return other;
}
}
2.3 返回当前对象的引用
const Human& Human::compare2(const Human& other) {
if (age > other.age) {
return *this; //访问该对象本身的引用,而不是创建一个新的对象
}
else {
return other;
}
}
参考资料:
436

被折叠的 条评论
为什么被折叠?



