Dziedziczenie i polimorfizm
Ostatnio zmodyfikowano 2017-04-18 13:13
MoravenTolo Temat założony przez niniejszego użytkownika |
Dziedziczenie i polimorfizm » 2017-04-17 18:05:32 Witam! Mam porobione klasy Monster, Player, Weapon i mam taki problem, gdyż muszę stworzyć metodę void Player::attack(Monster &monster), w ktorej należy sprawdzic ilosc zadanych obrazen przez posiadana bron. Jezeli liczba zadanych obrazen jest wieksza od zera, nalezy odpowiednio zredukowac zycie potwora. W klasie Monster jednym z parametrów jest życie potwora no i tworzac obiekt typu Monster życie to ma jakąś określoną wartość i nie wiem jak zmienić tą wartość (jak się do niej dostać) z tej funkcji atakującej. Pomoże ktoś? Zamieszczam kod i to co sam starałem się zrobić: Plik: Player.h #include <string> #include <vector> #include "Monster.h" #include "Weapon.h"
class Player { std::string name; int strength; int mana; int defence; double health; Weapon * weapon; public: Player( const std::string & name, int strength, int mana, int defence, double health ); virtual ~Player(); void attack( Monster & monster ); const std::string & getName() const void setName( const std::string & name ); void setWeapon( Weapon & weapon );
Plik: Player.cpp #include <iostream> #include "Player.h"
using std::string; using std::cout; using std::endl;
Player::Player( const string & name, int strength, int mana, int defence, double health ) : name( name ) , strength( strength ) , mana( mana ) , defence( defence ) , health( health ) { }
Player::~Player() { }
void Player::setWeapon( Weapon & weapon ) { Player::weapon = & weapon; }
void Player::attack( Monster & monster ) { double x; if(( weapon->getDamage( getStrength(), monster ) > 0 ) ) { x = monster.getHealth() - weapon->getDamage( getStrength(), monster ); } else x = monster.getHealth(); monster.setHealth( x ); }
Uzylem tej zmiennej x jako tej co zmienie wartosc zycia potwora, ale po pierwsze to nie dziala a po drugie musze chyba dzialac od razu na tej zmiennej zawartej w klasie Monster. Czekam na krytyke i pomoc. |
|
darko202 |
» 2017-04-18 13:13:21 1. >> po pierwsze to nie dziala czy możesz sprecyzować co nie działa ? na podstawie zaprezentowanego fragmentu kodu trudno się do tego odnieść. 2. zapoznaj się z technologia debugowania kodu https://msdn.microsoft.com/pl-pl/library/hh368280.aspxczęsto kod wykonuje się inaczej niż myślimy :) |
|
« 1 » |