Human.h
#pragma once #includeclass 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" #includeint 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" #includeint 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; }
运行结果:



