this指针一般使用的场景有两个:
1. 在自定义构造函数中使用;
2. 在对象的比较函数中使用;
具体代码如下:
Human.h文件
#include <iostream>
#include <string>
#include <Windows.h>
#define ADDR_LEN 64
using namespace std;
class Human{
public:
Human();
Human(string, int, int);
void eat();
void sleep();
void paly();
void work();
string getName(); // 获取名字
int getAge(); // 获取年龄
int getSalary(); // 获取薪水
void desprition(); // 描述
Human &compare1(Human &other);
Human *compare2(Human *other);
private:
string name;
int age;
int salary;
};
human.cpp
#include "Human.h"
Human::Human(string name, int age, int salary)
{
// this 指针的使用场景1
cout << "调用自定义的构造函数" << endl;
this->name = name;
this->age = age;
this->salary = salary;
}
void Human::eat()
{
cout << "我正在吃" << endl;
}
void Human::sleep()
{
cout << "我正在睡觉" << endl;
}
void Human::paly()
{
cout << "我正在玩" << endl;
}
void Human::work()
{
cout << "我正在工作" << endl;
}
string Human::getName()
{
return name;
}
int Human::getAge()
{
return age;
}
int Human::getSalary()
{
return salary;
}
void Human::desprition()
{
cout<< "name:" << name <<
" age:" << age <<
" salary:" << salary << endl;
}
Human &Human::compare1(Human &other)
{
// this指针的使用场景2(引用版本)
if(salary > other.salary){
return *this;
}else{
return other;
}
}
Human *Human::compare2(Human *other)
{
// this指针的使用场景2(指针版本)
if(salary > other->salary){
return this;
}else{
return other;
}
}
main.cpp
#include "Human.h"
int main(void)
{
Human h1("张三", 28, 30000);
Human h2("李四", 30, 35000);
h1.compare1(h2).desprition();
h1.compare2(&h2)->desprition();
system("pause");
return 0;
}