定义一个或多个类,来描述以下需求:
定义一个类,来表示某模拟养成游戏中人物:
每个人物,有呢称、年龄、性别、配偶、朋友,
支持的活动有:结婚、离婚、交友、断交、询问呢称、询问性别、询问年龄、简介等。
代码如下:
头文件声明代码:
#pragma once #include <iostream> #include <Windows.h> #include <string> #include <vector> #include <sstream> using namespace std; typedef enum { MAN,//男人 WOMAN//女人 }gender_t; class Human { public: Human(); Human(const string& name, int age, gender_t gender); ~Human(); string getName(); int getAge(); gender_t getGender(); string description(); Human* getSpouse(); vector<Human*> getFriends(); void marry(Human &other); void divorce(); void addFriends(Human& other); void delFriends(const Human &other); private: string name; int age; gender_t gender; Human* spouse;//聚合关系 vector<Human*> friends; };
Human.cpp文件代码:
#include "Human.h" Human::Human() { } Human::Human(const string& name, int age, gender_t gender) { this->name = name; this->age = age; this->gender = gender; } Human::~Human() { } string Human::getName() { return name; } int Human::getAge() { return age; } gender_t Human::getGender() { return gender; } string Human::description() { stringstream des; des << "姓名:" << name << "性别:" << (gender == 0 ? "男" : "女") << endl; return des.str(); } Human* Human::getSpouse() { return spouse; } vector<Human*> Human::getFriends() { return friends; } void Human::marry(Human& other) { if (gender == other.gender) { return; } this->spouse = &other; other.spouse = this; } void Human::divorce() { if (this->spouse == NULL) { return; } spouse->spouse = NULL; spouse = NULL; } void Human::addFriends(Human& other) { friends.push_back(&other); } void Human::delFriends(const Human& other) { for (auto it = friends.begin(); it != friends.end();) { if (*it == &other) { it = friends.erase(it); } else { it++; } } }
主函数代码:
#include "Human.h" Human::Human() { } Human::Human(const string& name, int age, gender_t gender) { this->name = name; this->age = age; this->gender = gender; } Human::~Human() { } string Human::getName() { return name; } int Human::getAge() { return age; } gender_t Human::getGender() { return gender; } string Human::description() { stringstream des; des << "姓名:" << name << "性别:" << (gender == 0 ? "男" : "女") << endl; return des.str(); } Human* Human::getSpouse() { return spouse; } vector<Human*> Human::getFriends() { return friends; } void Human::marry(Human& other) { if (gender == other.gender) { return; } this->spouse = &other; other.spouse = this; } void Human::divorce() { if (this->spouse == NULL) { return; } spouse->spouse = NULL; spouse = NULL; } void Human::addFriends(Human& other) { friends.push_back(&other); } void Human::delFriends(const Human& other) { for (auto it = friends.begin(); it != friends.end();) { if (*it == &other) { it = friends.erase(it); } else { it++; } } }