I am trying to teach myself C++ through the use of e-books and videos and I have a question on classes.
I am using a basic text based pokemon game as an example and I am trying to add a battle sequence.
The issue i am having is I am unable to reference my class in a new function as it seems its on an entire different scope. When I go to use it such as starter.move1 it will not recognize the class in a new function.
You mean the pokemon object created on line 41? Class objects follow the same scoping rules as any other type (int, char, std::string, etc.). If you declare it in one function it will not be in scope in other functions.
Consider passing the object by reference to the functions that use them, or if a function creates a new pokemon as firstpokemon() do then you could make it the return value.
I think I understand what you mean by passing it through by reference...
the issue I am having is how can I return all of those class values at once if I do that?
I use the funtion starterpokemon and in that function it declares 3 variables, how could I return all three of those
this is what I have
#include "stdafx.h"
#include <iostream>
#include <string>
usingnamespace std;
class pokemon
{
public:
string name;
int hp;
int level;
string move1;
string move2;
string move3;
string move4;
void attack();
};
pokemon firstpokemon(pokemon starter);
int main()
{
pokemon starter;
firstpokemon(starter);
cout << endl << endl << "Your starter pokemon is: " << starter.name << ". It is level: " << starter.level << endl;
char answer;
cout << "Do you want to make your way to Viridian City? (y/n) ";
cin >> answer;
switch(answer)
{
case'y':
break;
case'n':
cout << endl << "You stay at proffesor oaks lab!\n";
break;
}
}
pokemon firstpokemon(pokemon starter)
{
starter.hp = 10;
starter.level = 5;
int starternum = 0;
do {
cout << "Would you like to pick Charmander(1), Squirtel(2), or Bulbasaur(3): ";
cin >> starternum;
}while(starternum < 1 || starternum > 3);
switch(starternum)
{
case 1:
cout << "You chose charmander!\n";
starter.name = "Charmander";
starter.move1 = "scratch";
starter.move2 = "leer";
break;
case 2:
cout << "You chose squirtel!\n";
starter.name = "Squirtel";
starter.move1 = "Tackle";
starter.move2 = "Tail Whip";
break;
case 3:
cout << "You chose bulbasaur!\n";
starter.name = "Bulbasaur";
starter.move1 = "Tackle";
starter.move2 = "Growl";
break;
}
return starter;
}
This is my output:
1 2 3 4 5 6 7 8 9
Would you like to pick Charmander(1), Squirtel(2), or Bulbasaur(3): 1
You chose charmander!
Your starter pokemon is: . It is level: -858993460
Do you want to make your way to Viridian City? (y/n) n
You stay at proffesor oaks lab!
Press any key to continue . . .
I am not sure how I can return the level and name.