Hi, I wrote a very simple code, I want to display the name of the character, but I can't figure it out how I could. Thank you in advance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
class Player{
public:
Player(string name);
virtual ~Player();
virtual void fight() = 0;
private:
string _name;
};
Player::Player(string name){ _name = name;}
Player::~Player(){}
#include "Player.h"
#include <iostream>
using namespace std;
class Elf : public Player{
public:
Elf(string elf_name);
~Elf();
void fight(){
cout << "I kill you!" << endl;
}
protected:
string _elf_name;
};
Elf::Elf(string elf_name) : Player(elf_name){ _elf_name = elf_name;}
Elf::~Elf(){}
class Dwarf : public Player{
public:
Dwarf(string dwarf_name);
virtual ~Dwarf();
void fight(){
cout<< "Where's The Arkengem!?" << endl;
}
protected:
string _dwarf_name;
};
Dwarf::Dwarf(string dwarf_name) : Player(dwarf_name){_dwarf_name = dwarf_name;}
Dwarf::~Dwarf(){}
#include <iostream>
#include <vector>
#include "Player.h"
#include "Elf.h"
#include "Dwarf.h"
using namespace std;
int main(){
vector<Player*> playerGroup;
Elf* aElf = new Elf("Legolas");
Dwarf* aDwarf = new Dwarf("Gimli");
playerGroup.push_back(aElf);
playerGroup.push_back(aDwarf);
vector<Player*>::const_iterator itr;
for(itr = playerGroup.begin(); itr != playerGroup.end(); itr++){
cout << *itr; // FIXME
(*itr)->fight();
}
return 0;
}
|
Last edited on
Thank you, I would like to know if there's a way of solving it that doesn't require a change like this
Don't have name members in your derived classes, and add a getName() to Player class.
Thank you so much, it works!