C++面向对象的程序设计2——this指针的用处

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;
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值