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;
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];
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;
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) {
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;
}
}
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;
}