C++赋值,关系,下标运算符重载示例

Human.h

#pragma once
#include<string>
class Human{
public:
	Human(const char* name, int age, int salare,int DarkHouse);
	~Human();

	//注意返回值类型&,和参数类型&
	Human& operator=(const Human& other);

	//按薪资比较
	bool operator>(const Human& other);
	bool operator<(const Human& other);
	bool operator==(const Human& other);
	int operator[](std::string index);
	int operator[](int index);


	std::string description();
private:
	char* name;
	int age;
	int salare;
	int DarkHouse;
	unsigned int id;
	static int last_iD;
};

Human.cpp

#include "Human.h"
#include<sstream>

int Human::last_iD = 0;

Human::Human(const char* name, int age, int salare,int DarkHouse)
{
	if (!name) {
		name = "未命名";
	}
	this->name = new char[strlen(name) + 1];
	strcpy_s(this->name, strlen(name) + 1, name);
	this->age = age;
	this->salare = salare;
	this->DarkHouse = DarkHouse;

	this->id = ++last_iD;
}

Human::~Human()
{
	delete[] this->name;
}

Human& Human::operator=(const Human& other) {
	if (this->name) {
		delete[] this->name;
	}
	this->name = new char[strlen(other.name)+1];
	strcpy_s(this->name, strlen(other.name) + 1, other.name);
	this->age = other.age;
	this->salare = other.salare;
	this->DarkHouse = other.DarkHouse;
	this->id = other.id;
	return *this;
}

bool Human::operator>(const Human& other) {
	if (this->salare > other.salare)
		return true;
	else
		return false;
}
bool Human::operator<(const Human& other) {
	if (this->salare < other.salare)
		return true;
	else
		return false;
}
bool Human::operator==(const Human& other) {
	if (this->salare == other.salare)
		return true;
	else
		return false;
}

int Human::operator[](std ::string index) {
	if (index == "age")
		return age;
	else if (index == "salare")
		return salare;
	else if (index == "darkHouse")
		return DarkHouse;
	else
		return -1;
}

int Human::operator[](int index) {
	if (index == 0)
		return age;
	else if (index == 1)
		return salare;
	else if (index == 2)
		return DarkHouse;
}

std::string Human::description()
{
	std::stringstream ret;
	ret << "姓名:" << name << "\t年龄:" << age << "\t薪资:" 
		<< salare << "\t黑马值:" << DarkHouse << "\t编号:" << id << '\n';
	return ret.str();
}

main.cpp

#include"Human.h"
#include<iostream>

int main() {
	Human boy1("Rock", 38, 58000, 5);
	Human boy2("Jack", 25, 50000, 10);
	std::cout << "age:" << boy1["age"] << std::endl;
	std::cout << "salary:" << boy1["salare"] << std::endl;
	std::cout << "darkHorse:" << boy1["darkHouse"] << std::endl;
	

	std::cout << "[0]:" << boy1[0] << std::endl;
	std::cout << "[1]:" << boy1[1] << std::endl;
	std::cout << "[2]:" << boy1[2] << std::endl;


	system("pause");
	return 0;
}

运行结果:

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值