C++ Inheritance error - c++

Here's the code that triggers the error (Player.cpp):
#include "Library.h"
Player::Player(){
//generate player stats
str = rand()%6+1+1;
inte = rand()%6+1;
c = (rand()%6+1)+floor(str/3);
wis = rand()%6+1+floor(inte/4);
ref = rand()%6+1+floor(wis/4);
i = floor(ref/3);
hp = floor((str+(wis/3)+(ref/2)));
xp = 0;
}
//printStats (constant Player player reference)
//prints player's stats
void Player::printStats() const{
cout << "\nSTR: " << str << endl;
cout << "INTE: " << inte << endl;
cout << "C: " << c << endl;
cout << "WIS: " << wis << endl;
cout << "REF: " << ref << endl;
cout << "I: " << i << endl;
cout << "HP: " << hp << endl;
cout << "XP: " << xp << endl;
cout << "Gold: " << gold << endl;
cout << "Level: " << lvl << endl << endl;
}
int Player::giveOptions(int amount,string op1, string op2, string op3, string op4, string op5){
cout << "Type the number then press the enter key to choose or type 'help' for extra commands." << endl;
for(int i=1;i<=amount;i++){
string s;
switch(i){
case 1:
s = op1;
break;
case 2:
s = op2;
break;
case 3:
s = op3;
break;
case 4:
s = op4;
break;
case 5:
s = op5;
break;
}
cout << i << ". " << s << endl;
}
while(true){
string s;
cin >> s;
if (s == "1")
return 1;
else if (s == "2")
return 2;
else if (s == "3")
return 3;
else if (s == "4")
return 4;
else if (s == "5")
return 5;
else{
if (s == "stats")
printStats();
else if (s == "help"){
cout << "Type the number that is next to the option you wish to choose then press the enter key, or 'stats' to print all of your stats." << endl;
cout << "E.G:\n1. Town\nI want to go to the town\n1" << endl;
}
else
cout << "Command not recognised. If you're confused, type 'help'." << endl;
}
}
}
(Original question below)
I'm fairly basic in C++, and I'm not sure why this is producing an error. In Player.cpp, all members of Entity that I thought were inherited produce the error, "x is not a member of Player". My only thought is that I'm using inheritance wrong.
Entity.h:
#include "Library.h"
using namespace std;
class Entity {
public:
void printStats() const;
protected:
//player stats
std::string name;
double str; //strength
double wis; //wisdom
double ref; //reflex
double hp; //health points
double i; //initiative
double inte; //intelligence
double c; //courage
int gold; //gold
int xp; //experience
int ap; //armour points
int wd; //weapon damage
int lvl; //level
int sp; //skill points
};
Player.h
#include "Library.h"
using namespace std;
class Player: public Entity{
public:
Player();
int giveOptions(int amount, string op1, string op2, string op3, string op4, string op5);
};

void Player::printStats() const
Should be, according to your headers:
void Entity::printStats() const
On the includes, do one of these, whichever suits your code best:
1.
Player.h must include Entity.h
Library.h should not include Player.h or Entity.h
Player.h and/or Entity.h can include Library.h if really needed.
or 2.
Player.h must include Entity.h, but not Library.h
Entity.h must not include Library.h
Library.h can include Player.h and/or Entity.h
This avoids the cyclic dependencies you currently have - which leads to Player being defined before Entity and giving the base class undefined error.

As the compiler compliains - neither the class Entity nor the Player has a member variable called x. You need to include "Entity.h" in the Player header file, since in the current translation unit compiler doesn't know what Player is.

Related

I have different output from the same code on Linux VSCode (gcc) and Windows Clion (visual c++)

I've made a text based game for my project in VSCode (gcc). The main problem is that VSCode gives me strange output while Clion (visual-c++) gives me the right one.
For example in VSCode I get negative numbers as my damage while in Clion I get the right ones.
I hope the code that I provided will help you to find the reason to this strange behaviour
I want to know how to fix this problem and how to avoid it in the near future. Thank you in advance
Main.cpp
#include <iostream>
#include <vector>
#include <ctime>
#include <string>
#include <algorithm>
#include "mob.h"
using namespace std;
int main()
{
//Random seed
srand(time(nullptr));
//Player Initialization
//Mobs Initialization
mob Skeleton{rand()%51+50, rand()%21+30, rand()%11, "Skeleton", rand()%11+10};
mob Zombie{rand()%101+100, rand()%11+10, rand()%21, "Zombie", rand()%11};
mob Spider{rand()%21+30, rand()%11+20, rand()%11, "Spider", rand()%21+50};
mob Creeper{rand()%16+5, rand()%51+50, 0, "Creeper", rand()%6};
//Array of mobs
vector <mob> mobs;
mobs.push_back(Skeleton);
mobs.push_back(Zombie);
mobs.push_back(Spider);
mobs.push_back(Creeper);
//Fight
int CurrentAttack = 0, n;
while (1 < mobs.size())
{
//Mobs order output
cout << endl << mobs[0].name << endl;
cout << "Choose who to attack:" << endl;
tryAgain: //In case if user typed wrong number
for (int q = 1; q < mobs.size(); q++)
{
cout << q << " - " << mobs[q].name << endl;
}
//Choose who to attack
cin >> n;
switch (n)
{
case 1:
{
mobs[0].Attack(CurrentAttack);
mobs[1].TakeHit(CurrentAttack);
mobs[1].Return();
break;
}
case 2:
{
if (n > mobs.size()-1)
{ printf("This enemy is already dead");
goto tryAgain;
}
mobs[0].Attack(CurrentAttack);
mobs[2].TakeHit(CurrentAttack);
mobs[2].Return();
break;
}
case 3:
{
if (n > mobs.size()-1)
{
cout << "This enemy is already dead" << endl;
goto tryAgain;
}
mobs[0].Attack(CurrentAttack);
mobs[3].TakeHit(CurrentAttack);
mobs[3].Return();
break;
}
default:
goto tryAgain;
}
if (mobs[n].Health() == 0)
{
//Remove dead mob
rotate(mobs.begin(),mobs.begin()+n+1,mobs.end());
mobs.pop_back();
}
else
{
//Rotate Vector for different mob to attack
rotate(mobs.begin(),mobs.begin()+1,mobs.end());
}
}
cout << "⣿⣿⣿⣿⡿⠟⠛⠛⠛⠛⠉⠉⠙⠛⠛⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠟" << endl << "⣿⣿⣯⣥⣤⣶⣶⣶⣶⣿⣿⣿⣿⣿⣿⣷⣾⣿⣿⣿⣿⣿⣿⣿⣏⣀⣀⣀⡀" << endl << "⣿⣿⣿⣿⣿⣿⣿⡿⠿⠛⠛⠻⠿⠟⠉⠉⠉⢻⣿⣿⣿⡿⠟⠋⣡⣼⣿⣿⣿⡄" << endl
<< "⣿⣿⣿⣟⣭⣤⣶⣶⣿⣿⠃⠀⠀⢀⣀⣤⣶⣿⣿⣿⣿⡅⡀⢀⣩⣤⣤⠀" << endl << "⣿⣿⣿⣿⣿⣿⣛⡛⠛⠛⠛⢋⣩⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣛⠛⠛⠓⠠" << endl << "⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⣤⣤⣤⣦" << endl
<< "⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇" << endl << "⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠿⠿⠿⢿⡿⢿⣿⣿⣿⠃" << endl << "⠿⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣥⣄⣀⣀⠀⠀⠀⠀⠀⢰⣾⣿⣿⠏" << endl
<< "⠀⠀⠀⠀⠀⠀⠉⣩⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣜⡻⠋" << endl << "⣰⣾⣷⣶⣿⣾⣖⣻⣿⣿⡿⣿⣿⣿⣿⠿⠿⠟⠛⠛⠛⠋⠉⠉⢉⡽⠃" << endl << "⣿⣿⣿⣿⣿⣿⡉⠉⠉⠛⠛⠛⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⡤⠚⠉" << endl
<< "⠛⠛⣿⣿⣿⣿⣿⣿⣿⠉⠛⢶⣶⣄⠀⠀⠀⠀⠀⠀⠀⠀⡇" << endl << "⠠⣾⣿⣿⣿⣿⣿⠿⠟⠃⠀⠀⠀⠈⠲⣴⣦⣤⣤⣤⣶⡾⠁" << endl << "⠄⠈⠉⠻⢿⣿⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠛⠛⠉⠀" << endl;
cout << endl << mobs[0].name << " has survived!" << endl;
return 0;
}
Mob.h
#ifndef TEXTRPG_MOB_H
#define TEXTRPG_MOB_H
#include <string>
#include <iostream>
using namespace std;
class mob {
int health;
int damage;
int armor;
int attack = 0;
int agility;
void Damage(int attack);
//Types of Attack
void StrongAttack(int& CurrentAttack);
void SmallAttack(int& CurrentAttack);
void Crit(int& CurrentAttack);
public:
string name;
void Return();
void GiveAttack(int& CurrentAttack);
void Attack(int& CurrentAttack);
void TakeHit(int attack);
bool Health();
mob(int health, int damage, int armor, string name, int agility);
};
#endif
Mob.cpp
#include "mob.h"
using namespace std;
//Attack function
void mob::Attack(int& CurrentAttack) {
int n;
cout << "Choose what attack to use:\n1 - Strong Attack;\n2 - Simple Attack;\n3 - Critical Strike;\n";
cin >> n;
switch (n) {
case 1:
StrongAttack(CurrentAttack);
break;
case 2:
SmallAttack(CurrentAttack);
break;
case 3:
Crit(CurrentAttack);
break;
default:
SmallAttack(CurrentAttack);
break;
}
}
//Types of Attack
void mob::StrongAttack(int& CurrentAttack)
{
this -> attack = damage*2;
mob::GiveAttack(CurrentAttack);
}
void mob::SmallAttack(int& CurrentAttack)
{
this -> attack = damage;
mob::GiveAttack(CurrentAttack);
}
void mob::Crit(int& CurrentAttack)
{
if (rand() % 2)
{
this -> attack = damage*3;
mob::GiveAttack(CurrentAttack);
};
}
//Share Attack to main.cpp
void mob::GiveAttack(int& CurrentAttack)
{
CurrentAttack = attack;
}
//TAKE HIT
//Take damage from other mob
void mob::TakeHit(int attack)
{
if (rand()%101 > agility)
{
Damage(attack);
}
else
{
this -> attack = 0;
cout << "You missed" << endl;
}
}
void mob::Damage(int attack) //Health calculation
{
//Damage Calculation
if (attack - armor <= 0)
this -> attack = 0;
else
this -> attack -= armor;
//Health calculation
if (health - attack <= 0)
{
cout << name << " is dead" << endl;
this -> health = 0;//Health < 0 -> Death
}
else
this -> health -= attack; //Health Calculation
}
//Public
void mob::Return()
{
cout << name << " took " << attack << " damage" << endl;
cout << name << " has " << health << " HP left" << endl;
}
bool mob::Health()
{
if (health == 0)
return 0;
else
return 1;
}
//Constructor
mob::mob(int health, int damage, int armor, string name, int agility)
{
this -> health = health;
this -> damage = damage;
this -> armor = armor;
this -> name = name;
this -> agility = agility;
}

Accessing variables in base class C++

Hi this is the header file for my base class Ranger, and in it I have protected variables fov_, usb_ ... that I wish to access with my getter functions, I have three child classes on this one.
Ranger.h
#ifndef RANGER_H
#define RANGER_H
using namespace std;
class Ranger
{
//private contructor prevents contruction of base class
Ranger();
public:
void setBaud(int baud);
virtual void setFOV(int fov) = 0;
void setSamp(int sam);
int getFOV();
int getBaud();
int getMaxRange();
int getUSB();
protected:
//protected variables that are each indivdualy owned by each sensor
int fov_;
int maxRange_;
int usb_;
int baud_;
int samp_;
double data[];
//protected contructors for the child classes to use to set fixed parameters
Ranger(int fov, int maxRange, int port);
Ranger(int maxRange, int port);
};
#endif // RANGER_H
This is my cpp file for the base class that includes the getter files, it just has a return of the portected variables.
Ranger::Ranger()
{
}
Ranger::Ranger(int fov, int maxRange, int port)
{
fov_ = fov;
maxRange_ = maxRange;
usb_ = port;
}
Ranger::Ranger(int maxRange, int port)
{
maxRange_ = maxRange;
usb_ = port;
}
void Ranger::setBaud(int baud)
{
switch(baud)
{
case 0: baud_ = 38400; break;
case 1: baud_ = 115200; break;
default: baud_ = 38400; break;
}
}
void Ranger::setSamp(int sam)
{
samp_ = sam;
}
int Ranger::getFOV()
{
return fov_;
}
int Ranger::getBaud()
{
return baud_;
}
int Ranger::getMaxRange()
{
return maxRange_;
}
int Ranger::getUSB()
{
return usb_;
}
And in my main I want to access the protected variables from the base class to prevent re writting code, so each childs variables are protected in the base class. I try to access these by las.getFOV() but I get a segmentation fault error meaning I don't have access to them, and I don't quite understand why.
main.cpp
int main( int argc, char ** argv)
{
Laser las;
int baud;
cout << "Baud:" << endl;
cout << "0 - 38400" << endl;
cout << "1 - 115200" << endl;
cin >> baud;
las.setBaud(baud);
cout << "Baud for Lazer sensor is "+las.getBaud() << endl;
cout << "Lazer sensor created..." << endl;
cout << "Lazer's FOV: " + las.getFOV() << endl;
cout << "Lazer's Max Range: " + las.getMaxRange() << endl;
cout << "Lazer's Port: " + las.getUSB() << endl;
Radar rad;
int baud2;
cout << "Baud:" << endl;
cout << "0 - 38400" << endl;
cout << "1 - 115200" << endl;
cin >> baud2;
rad.setBaud(baud2);
cout << "Baud for Radar sensor is "+rad.getFOV() << endl;
int fov;
cout << "Feild of View Of Radar:" << endl;
cout << "0 - 20 degrees" << endl;
cout << "1 - 40 degrees" << endl;
cin >> fov;
rad.setFOV(fov);
cout << "FOV is set to " + rad.getFOV() << endl;
cout << "Radar sensor created..." << endl;
cout << "Radar's FOV: ' " + rad.getFOV() << endl;
cout << "Radar's Max Range: " + rad.getMaxRange() << endl;
cout << "Radar's Port: " + rad.getUSB() << endl;
Sonar son;
//rad.setFOV(user);
}
and here is one of the child class's cpp file for reference (Lazer)
laser.cpp
#include "laser.h"
Laser::Laser() : Ranger(180,8,0)
{
};
void Laser::setFOV(int fov)
{
fov_ = fov;
}
laser.h
#ifndef LASER_H
#define LASER_H
#include "ranger.h"
#include "rng.h"
class Laser : public Ranger
{
public:
Laser();
void setFOV(int fov);
};
#endif // LASER_H
Thanks everyone who commented, I understand I put way too much code to help you guys out, sorry about that I'll know for next time, and thankyou to letting me know the difference between the errors, I've done more research and found that the issue was when I was printing it out you can't use operators like:
cout<<""+function()<<endl;
Instead you need to separate the functions from the array like so:
cout<<""<<function()<<endl;
Thanks guys.

C++ Method won't call correct information from variable

I am working a a text adventure and have come across an error when I try to call a method from another method. The method returns the private int player_health and private int player_attack this work when I call it in main but when I call it in my combat_handler class it just give me a random number. I call it the exact same way in both class. Here is my code
Main.cpp
#include <iostream>
#include "player_handler.h"
#include "enemy_handler.h"
#include "combat_handler.h"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
player_handler phobj;
enemy_handler ehobj;
combat_handler cbobj;
phobj.test_player_systems();
ehobj.test_enemy_stats();
cbobj.player_turn();
phobj.get_player_stats();
return 0;
}
player_handler header
#ifndef PLAYER_HANDLER_H
#define PLAYER_HANDLER_H
class player_handler
{
public:
player_handler();
int get_player_health();
int get_player_attack();
void get_player_stats();
void add_player_health(int x);
void remove_player_health(int x);
void add_player_attack(int y);
void set_player_stats(int x, int y);
int test_player_systems();
private:
int player_health;
int player_attack;
};
#endif // PLAYER_HANDLER_H
player_handler.cpp
#include "player_handler.h"
#include <iostream>
using namespace std;
player_handler::player_handler()
{
//cout << "working"<< endl;
}
//Getting the players stats
int player_handler::get_player_health()
{
return player_health;
}
int player_handler::get_player_attack()
{
return player_attack;
}
void player_handler::get_player_stats()
{
cout << "the players health is " << get_player_health()<<endl;
cout << "The players attack is " << get_player_attack() <<endl;
}
//setting the player stats
void player_handler::set_player_stats(int x, int y)
{
player_handler::player_health = x;
player_attack = y;
//cout << "player health is " << player_health << endl;
//cout << "player attack is " << player_attack << endl;
}
//Player health control
void player_handler::add_player_health(int x)
{
//cout << "The old player health was " << player_health << endl;
player_health = player_health + x;
//cout << "Your health is now " << player_health << endl;
}
void player_handler::remove_player_health(int x)
{
//cout << "you lost " << x << " health" << endl;
player_health = player_health - x;
//cout << "Your new health is " << player_health << endl;
}
//player attack control
void player_handler::add_player_attack(int y)
{
//cout << "Your attack has been upgraded by " << y << " points" << endl;
player_attack = player_attack+y;
//cout << "You attack is now " << player_attack <<endl;
}
//test all player systems
int player_handler::test_player_systems()
{
set_player_stats(10,10);
cout <<"The player health is " << get_player_health()<<endl;
cout <<"the player attack is " << get_player_attack() << endl;
add_player_health(5);
remove_player_health(5);
add_player_attack(5);
get_player_stats();
return 0;
}
Now keep in mind that all this works it returns the right value for player_health and player_attack. now here is my problem it just gives me a random number
combat_handler header
#ifndef COMBAT_HANDLER_H
#define COMBAT_HANDLER_H
class combat_handler
{
public:
combat_handler();
int player_turn();
int enemy_turn();
private:
int player_input;
int player_dmg_given;
int enemy_dmg_given;
};
#endif // COMBAT_HANDLER_H
combat_handler.cpp
#include "combat_handler.h"
#include <iostream>
#include "player_handler.h"
using namespace std;
combat_handler::combat_handler()
{
cout << "combat handler on-line\n";
}
int combat_handler::player_turn()
{
player_handler phobj;
cout << "Would you like to (1)check stats (2) Enter the room?\n";
cin >> player_input;
switch(player_input){
case 1:
cout << "one"<<endl;
phobj.get_player_stats();
break;
default:
cout << "entering the room.\n";
break;
}
return 0;
}
The error happens when I call get_player_stats from the phobj in the combat handler class.
player_handler phobj;
This would call default constructor for player_handler( from your code it seems you are doing nothing in default constructor). And then you are calling get_player_stats() without setting the values. So, it would surely give you random values.
Earlier in main,
phobj.test_player_systems(); <<<< This is setting values.
phobj.get_player_stats(); <<<< Then you are querying on values already set.

C++ How to declare my array and other integers in a different cpp file from where they are filled?

So heres what im trying to do with my text based rpg now. I want to clean up my main.cpp so that it isnt so long and cluttered, so I am creating a few different cpp files that will hold related items.
I have a maketoon.cpp file that will go through some switch statements that will set all the modifiers(str, int, agl, maxhp) based on the class they choose(class being like lumberjack doctor etc not classes in the object sense of things).
when setting the variables in the maketoon.cpp(within a function called makeMainPlayer() ) i use setters that i made within my createcharacter.h file.
So before you look at my code below, i have a few questions.
1)Where should i create the object(main.cpp, maketoon.cpp). Currently i was creating the object Player in the maketoon.cpp file but im getting these errors:
||=== Build: Debug in 6_days_to_escape (compiler: GNU GCC Compiler) ===|
C:\...\maketoon.cpp||In function 'int makeMainPlayer()':|
C:\...\maketoon.cpp|5|error: 'startChoices' was not declared in this scope|
C:\...\maketoon.cpp|6|error: 'name' was not declared in this scope|
C:\...\main.cpp||In function 'int main()':|
C:\...\main.cpp|39|error: 'Player' was not declared in this scope|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
2)Should i capitalize the first letting in my object name?
3)how do i call makeMainPlayer in my main.cpp so set that specific objects values to then start the game?
4)Lastly, when i was testing to see if the setters and getters were working, i was getting another Player not declared in this scope error, so i tried just banging out another CreateCharacter Player;at the start of my int main, but i feel that will overwrite all the values set in the later functions, with the default null values.
Also. I know nothing about pointers, but if that is the best way to go(some google searches popped up with this as a fix to similar scenarios)
Seriosly thanks a ton! Im trying to teach myself OOc++ and it is proving difficult. Getting lost in the online tuts and youtube tuts.
//main.cpp
//game rpg
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <conio.h>
#include "createcharacter.h"
#include "maketoon.cpp"
using namespace std;
//is running check
bool running = 1;
//int healedHP(int x, int y);
//int attackedHP(int x, int y);
//user input var+
int userInput = 0;
int startChoices[4] = {0, 0, 0, 0};
string name;
//function declarations
void theStart();
void newGame();
int main (){
void makeMainPlayer();
cout << "Enter your name." << endl;
cin >> name;
cout << "Welcome " << name << "." << endl;
cout << "Strike any key....if you dare......";
getch();
system("cls");
theStart();
makeMainPlayer();
cout << "Name: " << Player.getplayerName() << endl;
cout << "Health: " << Player.getplayerHealth() << endl;
cout << "Strength: " << Player.getStr() << endl;
cout << "Int: " << Player.getInt() << endl;
cout << "Agility: " << Player.getAgl() << endl;
cout << "Difficulty: " << Player.getDifficulty() << endl;
system("pause");
return EXIT_SUCCESS;
}
void theStart()
{
cout << "\n\n";
cout << "\t6 Days to Escape!\n"; //title
cout << "\t\t 1: Play\n"; //main menu options. The first thing the user sees.
cout << "\t\t\t 2: Exit\n";
cin >> userInput;
system("cls");
if(userInput == 1)
{
// Create a new game
newGame();
}
else
{
//bool then false causeing program to exit
running = 0;
}
return;
}
void newGame(){
// there are 4 addresses in this array for the following:
//0. Difficulty
//1. Class
//2. Starting Wep
//3. Boost not implimented yet TODO
//enum class difficulty{simple, easy, hard, impossible};
do{
cout << "Choose Your difficulty: " << endl;
cout << "\t1. Simple - Game practically plays itself." << endl;
cout << "\t2. Easy - Not that easy." << endl;
cout << "\t3. Hard - Zombies do more than crave flesh." << endl;
cout << "\t4. Impossible - You will not make it." << endl;
cin >> startChoices[0];
cout << endl;
system("cls");
if(startChoices[0] < 1 || startChoices[0] > 4){
cout << "Invalid Difficulty Choice. Try again." << endl;}
}while(startChoices[0] < 1 || startChoices[0] > 4);
do{
cout << "Choose your class:" << endl;
cout << "\t1. Lumber Jack - Stong, hard to kill, but slow." << endl;
cout << "\t2. Doctor - Healer, weak but fast. Favors health." << endl;
cout << "\t3. Theif - FAST, Cunning but weak attacks." << endl;
cout << "\t4. Everydayer - Balenced everything." << endl;
cin >> startChoices[1];
cout << endl;
system("cls");
if(startChoices[1] < 1 || startChoices[1] > 4){
cout << "Invalid Class Choice. Try again." << endl;}
}while(startChoices[1] < 1 || startChoices[1] > 4);
do{
cout << "Choose your starting Weapon:" << endl;
cout << "\t1. Axe" << endl;
cout << "\t2. Crowbar" << endl;
cout << "\t3. Swiss army knife" << endl;
cout << "\t4. Ice pick" << endl;
cin >> startChoices[2];
cout << endl;
if(startChoices[0] < 1 || startChoices[0] > 4){
cout << "Invalid Weapon Choice. Try again." << endl;}
}while(startChoices[2] < 1 || startChoices[2] > 4);
}
//----------------------------------------------------------------------------------------
//createcharacter.h
#ifndef CREATECHARACTER_H
#define CREATECHARACTER_H
class CreateCharacter{
public:
//setter
void setplayerName(std::string x){
playerName = x;}
void setwepSpeed(int v){
wepSpeed = v;}
void setplayerHealth(int h){
playerHealth = h;}
void setplayerMaxHealth(int mh){
playerMaxHealth = mh;}
void setplayerStr(int s){
playerStr = s;}
void setplayerAgl(int a){
playerAgl = a;}
void setplayerInt(int i){
playerInt = i;}
void setplayerDifficulty(int d){
playerDifficulty = d;}
void setwepbaseDmg(int j){
wepbaseDmg = j;}
//getters
std::string getplayerName(){
return playerName;}
int getplayerHealth(){
return playerHealth;}
int getMaxHealth(){
return playerMaxHealth;}
int getStr(){
return playerStr;}
int getAgl(){
return playerAgl;}
int getInt(){
return playerInt;}
int getDifficulty(){
return playerDifficulty;}
private:
std::string playerName;
int playerHealth;
int playerMaxHealth; //absolute max = 200
int playerStr; // absolute max = 20
int playerAgl;// absolute max = 20
int playerInt;// absolute max = 20
int playerDifficulty; // absolute max = 4
//items
int wepbaseDmg;
int wepSpeed;
};
#endif
//------------------------------------------------------------------------------
//maketoon.cpp
//This was my attempt based off google....
//int* startChoices[4]={getDifficulty(), get};
int makeMainPlayer(){
CreateCharacter Player;
Player.setplayerDifficulty(startChoices[0]);
Player.setplayerName(name);
switch(startChoices[1]){
case 1:
Player.setplayerMaxHealth(175);
Player.setplayerStr(18);
Player.setplayerAgl(10);
Player.setplayerInt(6);
break;
case 2:
Player.setplayerMaxHealth(200);
Player.setplayerStr(9);
Player.setplayerAgl(13);
Player.setplayerInt(15);
break;
case 3:
Player.setplayerMaxHealth(100);
Player.setplayerStr(11);
Player.setplayerAgl(20);
Player.setplayerInt(10);
break;
case 4:
Player.setplayerMaxHealth(150);
Player.setplayerStr(12);
Player.setplayerAgl(12);
Player.setplayerInt(13);
break;
}
switch(startChoices[2]){
case 1:
Player.setwepbaseDmg(40);
Player.setwepSpeed(4);
break;
case 2:
Player.setwepbaseDmg(30);
Player.setwepSpeed(5);
break;
case 3:
Player.setwepbaseDmg(25);
Player.setwepSpeed(8);
break;
case 4:
Player.setwepbaseDmg(20);
Player.setwepSpeed(10);
break;
}
return 0;
}

How to Access a Dynamic struct from an external function C++?

I'm trying to make a very simple text-based game and I encountered an error when I tried to access a dynamic struct from an external function. I initialized all variables and structs in my header file and declared a dynamic alloc in the main function. But still I got errors. Am I missing something? This is my code.
==================main function "new.cpp"====================
#include <stdlib.h>
#include <iostream>
#include <string>
#include "game.h"
using namespace std;
difficulty _df_1;
player* player_1 = new player[3];
int main()
{
//initialize player stats
player_1->hp = 100;
player_1->life = 3;
player_1->mana = 50;
player_1->player_id = 1;
player_1->level = 1;
player_1->player_name= "emmet";
//..end
int turn=1;
cout << "What is your name? <<<";
getline(cin,player_1->player_name,'\n');
cout << "Choose a difficulty level: [0]Easy [1]Normal [2]Godlike" << endl;
int ch;
cin >> ch;
switch(ch)
{
case 0:
cout << "Scardy Cat chose EASY." << endl;
break;
case 1:
cout << "A really nice way to start. NORMAL" << endl;
break;
case 2:
cout << "Overly Manly Man is playing GODLIKE." << endl;
break;
default: cout << "I wonder how you can play this game if you can even read simple instructions."<< endl;return 0; break;
}
while(turn == 1)
{
char ch;
cout << "What do you want to do now? \n <<<<";
cin >> ch;
cin.ignore(5,'\n');
switch(ch)
{
case 'a': case 'A':
player_stat();
break;
case 'v': case 'V':
cheat_menu();
break;
case 'x': case 'X':
return 0;
break;
case '`':
break;
default: cout << "We were unable to process your request. Please try again" << endl; break;
}
}
delete player_1;
return 0;
}
void cheat_menu()
{
cout << "CHEATERS WILL ROT IN THE DEEPEST DEPTHS OF TARTARUS." << endl;
cout << "Enter Code:" << endl;
string cheat;
getline(cin,cheat,'\n');
if(cheat == "poo")
{
system("sleep 3");
cout << "Cheat Activated.." << endl;
player_1->hp += 1000;
player_1->level += 10;
player_1->mana += 1000;
player_stat();
}
else
{
cout << "Wrong cheat code.." << endl;
}
//system("sleep 3");
//system("clear");
}
==================end main function==============
=======external func "player_stat.cpp"===========
#include <iostream>
#include "game.h"
using namespace std;
void player_stat()
{
cout << "Name: " << player_1->player_name << endl
<< "Hp: " << player_1->hp << endl
<< "Life: " << player_1->life << "\t Mana: " << player_1->mana << endl
<< "Level: " << player_1->level << "\t XP: " << player_1->xp
<< endl;
//system("sleep 3");
//system("clear");
}
==================end external func==============
==========header file "game.h"===================
#ifndef _GAME_
#define _GAME_
#include "player_stat.cpp"
using namespace std;
//function prototypes...
void player_stat();
void cheat_menu();
//structs for player and NPC
struct player
{
string player_name;
int life;
double atk;
double hp;
double mana;
int player_id;
int level;
long int xp;
string weapon_name;
double weapon_damage;
};
enum difficulty {EASY,NORMAL,GODLIKE};
#endif
===========end header file=======================
These are the errors I got. Please don't mind the other left out functions in int main(). :P
In file included from game.h:4
from new.cpp
in function `void player_stat()':
`player_1' undeclared (first use in this function)
(Each undeclared identifier is reported only once for each function it appears in.)
At global scope:
`player*player_1' used prior to declaration
You declare the variable using the extern storage specifier:
extern player* player_1;
This tells the compiler that the player_1 variable is defined somewhere else, and the linker will resolve it later.
Also as I noted you actually allocate three player objects. If you only need one then don't allocate three:
player* player_1 = new player;
However, that's not needed either, declaring a normal non-pointer variable will work just as fine:
player player_1;
Then in the other files you use extern to tell the compiler that the variable is defined somewhere else:
extern player player_1;
add
extern player* player_1;
to game.h
this will make the player_1 variable available across all the modules.
also remove
#include "player_stat.cpp"
you are not supposed to include any cpp files in the header files