gpt4 book ai didi

c++ - 枚举序列化? C++

转载 作者:太空宇宙 更新时间:2023-11-04 11:40:11 25 4
gpt4 key购买 nike

我想先从总体上说我是初学者,所以我可能看不到任何东西。

我的主要目标是能够将已定义类的对象输出到文件,以便在另一个实例中读取。

Player obj 被写入包含其所有变量的文件。 前惠普。全科医生,高清但我也有两个枚举类型

枚举英雄{法师、战士、盗贼};/enum RACE {HUMAN, ORC, ELF, DWARF, GNOME};

我一直在四处寻找,发现重载 << 和 >> 运算符是一种实现此目的的方法。我的问题是 >> 运算符不喜欢我的 HERO 和 RACE 类型。

这就是我的立场。

播放器.h

#pragma once
#include <iostream>

enum HERO {MAGE, WARRIOR, ROGUE};
enum RACE {HUMAN, ORC, ELF, DWARF, GNOME};
using namespace std;

class Player
{
public:
Player();
Player();
int returnHP();
int returnATK();
int returnDEF();
int returnGP();
HERO returnCLASS();
RACE returnRACE();
int setHP(int x);
int setGP(int x);
int setATK(int x);
int setDEF(int x);
HERO setCLASS(HERO x);
RACE setRACE(RACE x);
void setNAME(string namei);


private:
int hp;
int gp;
int def;
int atkdmg;
char name[30];
HERO playerClass;
RACE playerRace;
friend istream& operator >> (istream& in, Player& obj);
friend ostream& operator << (ostream& out, const Player& obj);
};

播放器.cpp

#include "Player.h"
#include <iostream>
#include <string>

using namespace std;

Player::Player(){

hp = 0;
gp = 0;
def = 0;
atkdmg = 0;
strcpy(name,"noname");
playerClass = WARRIOR;
playerRace = HUMAN;


}




istream& operator >> (istream& in, Player& obj)
{
in >> obj.hp;
in >> obj.gp;
in >> obj.def;
in >> obj.atkdmg;
in >> obj.name;
in >> obj.playerRace;
in >> obj.hp;

return in;
}
ostream& operator << (ostream& out, const Player& obj)
{
out << obj.hp;
out << obj.gp;
out << obj.def;
out << obj.atkdmg;
out << obj.name;
out << obj.playerRace;
out << obj.hp;
return out;
}

我知道这可能看起来像垃圾,但都是自学的。任何帮助表示赞赏!提前致谢!

最佳答案

解决问题的最简单方法是在为 Player 类定义流运算符之前为枚举类定义流运算符。例如,对于 RACE:

istream& operator >> (istream& in, RACE& race)
{
unsigned u = 0;
in >> u;
//TODO: check that u is a valid RACE value
race = static_cast<RACE>(u);
return in;
}

ostream& operator << (ostream& out, RACE race)
{
//TODO: check that race is a valid RACE value
unsigned u = race;
out << u;
return out;
}

出于兼容性/对称性原因,还应定义输出运算符。

关于c++ - 枚举序列化? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21691354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com