2014-02-11 167 views
1

我想開始我是一個初學者整體,所以我可能沒有看到什麼。枚舉序列化? C++

我的主要目標是能夠將定義類的對象輸出到要在另一個實例中讀取的文件。

例如

Player obj寫入包含所有變量的文件。 ex hp。 GP,高清 但我也有兩個枚舉類型

枚舉HERO {MAGE,戰士,盜賊};/ 枚舉RACE {人類,獸人,精靈,矮人,侏儒};

我一直在搜索,發現超載的< <和>>運營商將是一種方式來做到這一點。我的問題是>>操作符不喜歡我的HERO和RACE類型。

這就是我的立場。

Player.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); 
}; 

Player.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; 
} 

我明白,這可能看起來像垃圾,但是這一切都爲自學。任何幫助表示讚賞!提前致謝!

+1

TL; DR;爲什麼你要暴露**那麼多**代碼,對於這樣一個簡單的問題? –

回答

1

解決您的問題的最簡單方法是在爲您的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; 
} 

出於兼容性/對稱性原因,還應該定義輸出運算符。