重载运算符 笔记5
字符串也能做下标:重载运算符[ ]
Boy.h
|
#pragma once #include <string>
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);
int operator[](std::string index); int operator[](int index);
std::string description(void); 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 <string.h> #include <sstream>
int Boy::LAST_ID = 0; //初始值是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; //this->id = boy.id; //根据需求来确定是否要拷贝id 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; } }
int Boy::operator[](std::string index) { if (index == "age") { return age; } else if (index == "salary") { return salary; } else if (index == "darkHorse") { return darkHorse; } else if (index == "power") { return power(); } else { return -1; } }
int Boy::operator[](int index) { if (index == 0) { return age; } else if (index == 1) { return salary; } else if (index == 2) { return darkHorse; } else if (index == 3) { return power(); } else { return -1; } }
std::string Boy::description(void) { std::stringstream ret; ret << "ID:" << id << "\t姓名:" << name << "\t年龄:" << age << "\t薪资:" << salary << "\t黑马系数:" << darkHorse; return ret.str(); }
int Boy::power() const { // 薪资* 黑马系数 + (100 - 年龄) * 1000 int value = salary * darkHorse + (100 - age) * 100; return value; } |
main.cpp
|
#include <iostream> #include "boy.h"
int main(void) { Boy boy1("Rock", 38, 58000, 5); Boy boy2("Jack", 25, 50000, 10);
std::cout << "age:" << boy1["age"] << std::endl; std::cout << "salary:" << boy1["salary"] << std::endl; std::cout << "darkHorse:" << boy1["darkHorse"] << std::endl; std::cout << "power:" << boy1["power"] << std::endl;
std::cout << "[0]:" << boy1[0] << std::endl; std::cout << "[1]:" << boy1[1] << std::endl; std::cout << "[2]:" << boy1[2] << std::endl; std::cout << "[3]:" << boy1[3] << std::endl;
system("pause"); return 0; } |

浙公网安备 33010602011771号