Hey! I am new here, so keep in mind that I am also kinda new with the C++ language and therefore need an easy explanation for how to solve my problem!
I am trying to create a console program/game with a menu, were I can see the stats for my "spaceship", or add new ones. Also, if I got the time, I will try to add enemies that I can "fight against", and so forth! The reason why I am telling this, is because you might find that my solution will cause problems later on, if I will add more features like these!
SO, my problem is: How do I call a function, within a function, that are placed in two different source- and class files? This is how it looks like (BOLD text for file names and were the problem occur):
hiya,
you main issue (i think) is on line 152 you create a PlayerShip object and then do nothing with it.
If you wanted to access you ship from other parts of the program (which is what I think you're asking?), then you could consider perhaps making the Menu constructor take a PlayerShip object.
however i think you need to look at the design a bit. a menu object would not in theory need knowledge of the ship object.
edit: i'll knock something up for you if you want.
okay, like this:
you main might look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
cout << "Welcome to Space Fighter XL!" << endl;
string newName;
cout << "Enter the name of your mothership here: ";
cin >> newName;
PlayerShip myShip(newName, 20, 100);
Menu myMenu(myShip);
return 0;
}
Menu::Menu(PlayerShip playerShip)
: m_playerShip(playerShip)
{
do
{
cout << "|-----MENU-----|" << endl;
cout << "1.Info about your ship" << endl;
cout << "2. View all the fighters!" << endl;
cout << "3. Exit the game!" << endl;
cin >> choice;
switch (choice)
{
case 1:
{
// now you are free to get at the ship's data inside the menu object,
// but this doesn't seem right for a menu object to 'contain' a PlayerShip object, for example:
m_playerShip.displayInfo();
m_playerShip.getName();
break;
}
case 2:
{
cout << "You picked 2" << endl;
break;
}
case 3:
{
cout << "You picked 3" << endl;
break;
}
}
} while (choice < 4);
}
Menu::~Menu()
{
}
menu.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Menu
{
private:
int choice;
PlayerShip m_playerShip;
public:
Menu(PlayerShip pShip);
~Menu();
void displayMenu();
void displayInfo();
};
BUT, as i've said in the comments. this allows you to get hold of the ship's data in your menu class, but from a OO point of view it makes no sense whatsoever for a menu class to contain a PlayerShip class.
hope that helps a bit. sorry if i've misinterpreted you.
Yeah, the design might be kinda bad, so you might have a better option? For easier tasks I would use a case-switch menu, at all times, because I think they are super easy and functional. BUT now when I am working with classes and more advanced programming, another option would suit better?
Do you have another/better option to recommend? How do others create a menu, when working with several files and classes?