用法一
Human::Human(int age, int salary) {
this->age = age; //this是一个特殊的指针,指向这个对象本身
this->salary = salary;
name = "无名";
}
...
Human h1(21, 5000);
谁调用指向谁,这里this指向h1对象。
用法二
#include <iostream>
using namespace std;
class Human {
public:
Human(string name, int age, int salary);
int getAge() const;
const Human* compare(const Human*);
private:
string name;
int age;
int salary;
char *addr;
};
int Human::getAge() const {
return age;
}
const Human* Human::compare(const Human* other) {
if (age > other->age) {
return this;
}
else {
return other;
}
}
Human::Human(string name, int age, int salary) {
cout << "调用自定义构造函数" << endl;
this->name = name;
this->age = age;
this->salary = salary;
addr = new char[16];
strcpy_s(addr, 16, "China");
}
int main() {
Human h1("Andy", 28, 2000);
Human h2("Van", 23, 4500);
cout << h1.compare(&h2)->getAge() << endl;
return 0;
}
结果:28
用法三
#include <iostream>
using namespace std;
class Human {
public:
Human(string name, int age, int salary);
int getAge() const;
const Human& compare(const Human&);
private:
string name;
int age;
int salary;
char *addr;
};
int Human::getAge() const {
return age;
}
const Human& Human::compare(const Human& other) {
if (age > other.age) {
return *this;
}
else {
return other;
}
}
Human::Human(string name, int age, int salary) {
cout << "调用自定义构造函数" << endl;
this->name = name;
this->age = age;
this->salary = salary;
addr = new char[16];
strcpy_s(addr, 16, "China");
}
int main() {
Human h1("Andy", 28, 2000);
Human h2("Van", 23, 4500);
cout << h1.compare(h2).getAge() << endl;
return 0;
}