Error C2227,C2065, Class within a Class
I'm trying to structure my code like this main <- game <- 开发者_JAVA技巧player.
IF I write in main:
player* P;
P = new player;
P->move();
Everything works but when trying to move this code in to the game component I run in to problems.
Here is the parts of game.cpp I need help with.
#include "game.h"
#include <string>
using namespace std;
game::game(){
player* P;
P = new player;
};
void game::playerStuff(){
P->move(); //c2227+C2065
};
Here is a part of game.h
#include "player.h"
class game {
public:
game();
void playerStuff();
The issue is rather simple. Your pointer to the player (P
) is a local variable only visible/existing within your constructor. Add it as a class member instead to use it everywhere in your game class:
class game
{
private:
player *P;
public:
game();
// other stuff ...
}
P
needs to be a member of the game
class.
Currently, in your constructor here:
game::game(){
player* P;
P = new player;
};
P
is local to the ctor and disappears as soon as this function ends.
Solution
Make P
a member of game
:
class game {
private:
player * P;
public:
game();
~game(); // NOTE: I have added a destructor
void playerStuff();
}
And change the contructor:
game::game(){
P = new player;
};
Remembering of course, to delete it in the destructor:
game::~Game(){
delete P;
};
Of course, because you include <player.h>
, you don't need to allocate this object on the heap at all, and can use the stack instead, thereby negating the need to delete P
in the destructor.
EDIT: Here is an example showing using the stack, rather than allocating on the heap:
#include "player.h"
class game
{
private:
player P; // Note, we're not declaring a pointer.. we have a complete type here.
public:
game();
~game();
void playerStuff();
}; // eo class game
game.cpp
game::game()
{
// No need to allocate, it's already allocating on the stack
}; // eo ctor
game::~game()
{
// No need to delete, P will be deallocated along with this game class.
}; // eo dtor
void game::playerStuff()
{
P.move(); // note we're not using -> (pointer to member) here
} // eo playerStuff
Move #include "player.h" to game.cpp if you need only pointers or references on game.h. If you need to reference Player on game.h to declare a pointer, you can use a forward declaration, like:
class Player;
class game
{
Player *myPlayer;
};
精彩评论