永不迷失的真爱: this指针
- 谁调用了this指针, 那么this指针就指向谁
第一种
- 调用自己的数据变量
Human::Human(string name, int age, string sex){
this->age = age; //this是一个特殊的指针,指向这个对象本身
this->name = name;
this->sex = sex;
const char* addr_s = "China";
this->addr = new char[ADDR_LEN];
strcpy_s(this->addr, ADDR_LEN, addr_s);
}
第二种
- 函数返回值是引用
//函数的返回值是引用
const Human& Human::compare1(const Human &other) {
if (this->age > other.age) {
return *this; //没有创建新的对象
} else {
return other;
}
}
//函数的返回值是指针
const Human* Human::compare2(const Human *other) {
if (this->age > other->age) {
return this; //没有创建新的对象
} else {
return other;
}
}