【自用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;
}

上面两种代码,一种是用指针的,一种是用引用的,它们使用的符号稍微有一点不一样,大家要注意!!也要注意函数中传入参数的种类!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值