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
8 Answers
+ 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;
}
+ 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.
+ 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?
+ 2
Ill just post the code.
+ 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
+ 1
This is very smart I hope it works as I wanted. thank you so much!
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
0
Thank you