关系运算符的重载 > < ==

Boy.h

#pragma once
#include <string>

class Boy
{
public:
	Boy(const char* name = NULL, int age = 0, int salary = 0, int darkHouse = 0);
	~Boy();
	std::string description();

	//重载赋值运算符
	Boy& operator=(Boy& boy);
	//关系运算符重载
	bool operator>(const Boy &boy);
	bool operator<(const Boy& boy);
	bool operator==(const Boy& boy);
	char* name;
private:
	
	int age;
	unsigned int id;
	static int LAST_ID;	//LAST_ID = 0 非法
	int salary;
	int darkHouse;//黑马系数
	int power() const;		//综合实力,内部调用
};


Boy.cpp

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

int Boy::LAST_ID = 0;

Boy::Boy(const char* name, int age, int salary, int darkHouse) {
	if (!name) {
		name = "未命名";
	}

	this->name = new char[strlen(name) + 1]; //分配空间,+1 是字符串结束符
	strcpy_s(this->name, strlen(name) + 1, name);

	this->age = age;
	this->salary = salary;
	this->darkHouse = darkHouse;
	this->id = ++LAST_ID;
}

Boy::~Boy() {
	if (name) {
		delete name;
	}
}

//返回当前对象的引用
Boy& Boy::operator=(Boy& boy) {
	if (name) {
		delete name;	//释放原来内存
	}
	name = new char[strlen(boy.name) + 1];
	strcpy_s(this->name, strlen(boy.name) + 1, boy.name);

	this->age = boy.age;
	this->salary = boy.salary;
	this->darkHouse = boy.darkHouse;
	//this->id = boy.id		取决于需求

	return *this;
}



std::string Boy::description() {
	std::stringstream ret;
	ret << "ID:" << id << "\t姓名:" << name << "\t年龄:" << age
		<< "\t薪资:" << salary << "\t黑马系数:" << darkHouse;

	return ret.str();
}


bool Boy::operator<(const Boy& boy) {
	//设置比较规则
	//薪资 * 黑马系数 + (100-年龄) * 1000
	if (power() < boy.power()) {
		return true;
	}
	else
	{
		return false;
	}

}

bool Boy::operator==(const Boy& boy) {
	//设置比较规则
	//薪资 * 黑马系数 + (100-年龄) * 1000
	if (power() == boy.power()) {
		return true;
	}
	else
	{
		return false;
	}

}

bool Boy::operator>(const Boy& boy) {
	//设置比较规则
	//薪资 * 黑马系数 + (100-年龄) * 1000
	if (power() > boy.power()) {
		return true;
	}
	else
	{
		return false;
	}

}

int Boy::power() const {
	int ret;
	ret = salary * darkHouse + (100 - age) * 1000;
	return ret;
}

main.cpp

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

int main(void) {
	
	Boy boy1("lemn",20,20000,10);
	Boy boy2("jack", 40, 30000, 5);

	if (boy1 > boy2) {
		std::cout << "选择" << boy1.name << std::endl;
	}
	else if (boy1 == boy2) {
		std::cout << "难以选择" << std::endl;
	}
	else {
		std::cout << "选择" << boy2.name << std::endl;
	}
	system("pause");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值