0

Can I have some some help with this project?

Two objectives (P1 and P2) of class 'Players' will store variables with unique values each one(P1.damage=2, P2.damage=5 for example and 30 more The problem is that I want to pass these values in an other class 'MainGame' and access their variables from there. I tryied to use Inheritance but if class 'MainGame' needs to return a value will that value be of player1 or player2? Ex GetDamage() {return damage;}Player1.damage isnt possible https://code.sololearn.com/clkGa1cSQZaQ/?ref=app

5th Mar 2018, 1:29 PM
xaralampis_
xaralampis_ - avatar
8 ответов
+ 2
#include <iostream> using namespace std; /* In this code, MainGame is a friend class of Player, and so can access all the private members of the Player Class. Hope this helps. */ class Player { int damage, speed; public: void properties(); friend class MainGame; }; void Player::properties() { cin>>damage>>speed; } class MainGame { Player* instance; public: MainGame() {instance=nullptr;} void PlayWith(Player&); int GetDamage(); }; void MainGame::PlayWith(Player& P) { instance=&P; } int MainGame :: GetDamage() { if(instance!=nullptr) return instance->damage; else throw 0; // Indicates error during access. } int main() { Player Player1, Player2; Player1.properties(); Player2.properties(); MainGame Game; Game.PlayWith(Player1); // Play the game by selecting P1. cout<<Game.GetDamage(); return 0; }
5th Mar 2018, 3:58 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 4
Thats not what I meant. But it seems that I was not able to understand your query. But first, try changing void to int or to the type of damage variable.
5th Mar 2018, 3:25 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
Maybe you can try to make a derived class MainGame from base class Player, and in the function pass an object of type Player to access its damage variable?
5th Mar 2018, 2:27 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
Ill just post the code.
5th Mar 2018, 3:40 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
I accidently made that void now. Anyway would it be difficult for you sent edit my code and sent it to me? I think that I haven't understand your response. Sorry for bothering you
5th Mar 2018, 3:30 PM
xaralampis_
xaralampis_ - avatar
+ 1
This is very smart I hope it works as I wanted. thank you so much!
5th Mar 2018, 4:02 PM
xaralampis_
xaralampis_ - avatar
0
Let's say that I pass the objective into the class by reference> void GiveData(Player &P1){this->P1 = P1} //and I cal the method Player1. GiveData(Player1) //then at the getDamage function void GetDamage() { return P1.damage} /* this is leads to an error, I think because damage has already been declared by its mother function so it doesn't need an identifier behind it
5th Mar 2018, 2:58 PM
xaralampis_
xaralampis_ - avatar
0
Thank you
5th Mar 2018, 3:46 PM
xaralampis_
xaralampis_ - avatar