main.cpp
#include<iostream>
#include"Boy.h"
int main()
{
Boy boy1("森", 25, 100000, 10);
Boy boy2("Jack", 25, 50000, 10);
if (boy1>boy2)
{
cout << "选择boy1" << endl;
}
else if (boy1 == boy2)
{
cout << "难以选择" << endl;
}
else
{
cout << "选择boy2" << endl;
}
system("pause");
return 0;
}
Boy.h
#pragma once
#include<iostream>
#include<string>
using namespace std;
class Boy
{
public:
Boy(const char*name =NULL, int age=0,int salary=0,int darkHorse=0);
~Boy();
Boy&operator=(const Boy&boy);
bool operator>(const Boy&boy);
bool operator < (const Boy&boy);
bool operator==(const Boy&boy);
string description();
private:
char*name;
int age;
int salary;
int darkHorse; //黑马,潜力值
unsigned int id; //编号
static int LAST_ID;
int power()const;
};
boy.cpp
#include "Boy.h"
#include<sstream>
#define NUM 100
int Boy::LAST_ID = 0;
Boy::Boy(const char * name, int age, int salary, int darkHorse)
{
if (!name)
{
name = "为命名";
}
this->name = new char[strlen(name) + 1];
strcpy_s(this->name, strlen(name) + 1,name);
this->age = age;
this->salary = salary;
this->darkHorse = darkHorse;
this->id = ++LAST_ID;
}
Boy::~Boy()
{
if (name)
{
delete name;
}
}
Boy & Boy::operator=(const Boy & boy)
{
if (name)
{
delete name; //释放原来的内存
}
name = new char[strlen(boy.name) + 1];//分配新的内存
strcpy_s(name, strlen(boy.name) + 1, boy.name);
this->age = boy.age;
this->salary = boy.salary;
this->darkHorse = boy.darkHorse;
return*this;
}
bool Boy::operator>(const Boy & boy)
{
//设置比较规则:
//薪资*黑马系数+(100-年龄)*100
if (power()>boy.power())
{
return true;
}
else
{
return false;
}
}
bool Boy::operator<(const Boy & boy)
{
if (power()<boy.power())
{
return true;
}
else
{
return false;
}
}
bool Boy::operator==(const Boy & boy)
{
if (power()==boy.power())
{
return true;
}
else
{
return false;
}
}
string Boy::description()
{
stringstream ret;
ret << "ID:" << id << "\t姓名:" << name << "\t年龄:" << age << "\t薪资:"
<< salary << "\t黑马系数:" << darkHorse;
return ret.str();
}
int Boy::power() const
{
//薪资*黑马系数+(100-年龄)*100
int value = salary * darkHorse + (NUM - age)*NUM;
return value;
}