【自用21.】C++-this指针
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");
}
说明:在类的静态成员函数【后续学习】中,不能使用this指针!
#include <iostream>
#include <Windows.h>
#include <string>
#include <string.h>
using namespace std;
// 定义一个“人类”
class Human {
public:
Human();
Human(int age, int salary);
int getAge();
Human& compare1(Human& other);
private:
string name = "Unknown";
int age = 28;
int salary;
char* addr;
};
Human::Human() {
name = "无名氏";
age = 18;
salary = 30000;
}
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");
}
int Human::getAge() {
return age;
}
Human& Human::compare1(Human& other) {
if (age > other.age) {
return *this; //没有创建新的对象
}
else {
return other;
}
}
int main(void) {
Human h1(25, 30000);
Human h2(18, 8000);
cout << h1.compare1(h2).getAge() << endl;
system("pause");
return 0;
}
#include <iostream>
#include <Windows.h>
#include <string>
#include <string.h>
using namespace std;
// 定义一个“人类”
class Human {
public:
Human();
Human(int age, int salary);
int getAge();
Human* compare1(Human* other);
private:
string name = "Unknown";
int age = 28;
int salary;
char* addr;
};
Human::Human() {
name = "无名氏";
age = 18;
salary = 30000;
}
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");
}
int Human::getAge() {
return age;
}
Human* Human::compare1(Human* other) {
if (age > other->age) {
return this; //没有创建新的对象
}
else {
return other;
}
}
int main(void) {
Human h1(25, 30000);
Human h2(18, 8000);
Human* p;
p = &h1;
cout << p->compare1(&h2)->getAge() << endl;
system("pause");
return 0;
}
上面两种代码,一种是用指针的,一种是用引用的,它们使用的符号稍微有一点不一样,大家要注意!!也要注意函数中传入参数的种类!