题目:
定义一个或多个类,来描述以下需求:
定义一个类,来表示某模拟养成游戏中人物:
每个人物, 有昵称,年龄,性别, 配偶, 朋友,
支持的活动有:结婚,离婚, 交友,断交,询问昵称,询问性别,询问年龄, 简介等
实现:
1. 头文件
#pragma once
#include <string>
#include <vector>
typedef enum sex{
MAN,
WOMAN
}sex_t;
using namespace std;
class Player
{
public:
Player();
Player(string name,int age, sex_t sex);
void marry(Player &other);
void divoce(); //离婚
void makeFriends(Player &other);
void breakFriends(Player &other); //断交
string getName() const;
char getSex() const;
int getAge() const;
Player *getLover() const;
vector<Player *> getFriends() const;
string descripiton() const;
private:
string name;
int age;
sex_t sex;
Player *lover = NULL;
vector<Player *> friends;
};
2. 实现方法
#include "Player.h"
#include <sstream>
Player::Player() {
}
Player::Player(string name, int age, sex_t sex)
{
this->name = name;
this->age = age;
this->sex = sex;
}
void Player::marry(Player &other)
{
if (sex == other.sex) {
return;
}
this->lover = &other;
other.lover = this;
}
void Player::divoce()
{
if (&lover == NULL) {
return;
}
lover->lover = NULL;
lover = NULL;
}
void Player::makeFriends(Player &other)
{
friends.push_back(&other);
}
void Player::breakFriends(Player &other)
{
for(auto it = friends.begin(); it != friends.end();)
{
if (*it == &other) {
it = friends.erase(it); //删除,返回值指向下一个迭代器
}
else {
it++;
}
}
}
string Player::getName() const
{
return name;
}
char Player::getSex() const
{
return sex;
}
int Player::getAge() const
{
return age;
}
Player *Player::getLover() const
{
return lover;
}
vector<Player*> Player::getFriends() const
{
return friends;
}
string Player::descripiton() const
{
stringstream ret;
ret << name << "-" << (sex == MAN ? '男' : '女') << age << "岁";
return ret.str();
}
3. 调用
#include <iostream>
#include "Player.h"
int main() {
Player p1("郭靖", 20, MAN);
Player p2("黄蓉", 21, WOMAN);
Player p3("杨过", 18, MAN);
Player p4("小龙女", 17, WOMAN);
p1.marry(p2);
p1.makeFriends(p3);
p1.makeFriends(p4);
p3.marry(p4);
Player *who = p1.getLover();
cout << p1.getName() << "的配偶是:" << who->getName() << endl;
cout << who->getName() << "的配偶是:" << who->getLover()->getName() << endl;
cout << p3.getName() << "的配偶是:" << p3.getLover()->getName() << endl;
for (int i = 0; i < p1.getFriends().size(); i++) {
cout << p1.getName() << "的朋友有:" << p1.getFriends()[i]->getName() << endl;
}
p3.divoce();
if (p1.getLover() == NULL) {
cout << p1.getName() << "已离婚" << endl;
}
if (p3.getLover() == NULL) {
cout << p3.getName() << "已离婚" << endl;
}
p1.breakFriends(p3);
cout << "与朋友断交" << endl;
for (int i = 0; i < p1.getFriends().size(); i++) {
cout << p1.getName() << "的朋友有:" << p1.getFriends()[i]->getName() << endl;
}
return 0;
}