Question

I'd like to start off I'm a beginner overall and so I'm probably not seeing something.

My main goal is to be able to output an object of a defined class to a file to be read in another instance.

i.e

Player obj is written to a file including all its variables. ex hp. gp, def But I also have two enumerated typed

enum HERO {MAGE, WARRIOR, ROGUE};/ enum RACE {HUMAN, ORC, ELF, DWARF, GNOME};

I've been poling around and found that overloading the << and >> operators would be a way to do this. My issue is that the >> operator does not like my HERO and RACE types.

Here's where I stand.

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

I understand that this probably looks like garbage but it's all being self taught. Any help is appreciated! Thanks in advance!

Was it helpful?

Solution

The simplest way to solve your problem is to define the stream operators for your enum classes before you define them for your Player class. For instance, for 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;
}

The output operator should also be defined, for compatibility/symmetry reasons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top