栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

Human.h

#pragma once
#include
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

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

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

运行结果:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/347021.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号