2011-01-06 8 views
0

私はこのメインのようなコードを構造化しようとしています< - game < - player。エラーC2227、C2065、クラス内のクラス

私がメインで書く場合:

player* P; 
P = new player; 

P->move(); 

すべてが動作しますが、ゲームの構成要素には、このコードを移動しようとしたとき、私は問題に実行します。

ここに私は助けが必要なgame.cppの部分です。ここで

#include "game.h" 

#include <string> 
using namespace std; 

game::game(){ 
    player* P; 
    P = new player; 
}; 


void game::playerStuff(){ 
P->move(); //c2227+C2065 
}; 

あなたはgame.h.上の唯一のポインタや参照が必要な場合game.cppするgame.h

#include "player.h" 

class game { 

public: 

    game(); 
    void playerStuff(); 
+0

:ここでは、スタックを使用して示すのではなく、ヒープ上の割り当て例があります正確に。それはコンパイラエラーですか、もしあなたがそれを投稿することができますか? –

答えて

0

移動する#include "player.h" の一部であり、ポインタを宣言するためにgame.hのPlayerを参照する必要がある場合は、次のような前方宣言を使用できます。

class Player; 

class game 
{ 
    Player *myPlayer; 
}; 
+0

ありがとう、私は必要な前方宣言だった! – snackbar

5

問題はかなり単純です。プレーヤーへのポインタ(P)は、コンストラクタ内でのみ表示/存在するローカル変数です。あなたのゲームクラスでどこでもそれを使用する代わりに、クラスのメンバとして追加します。

class game 
{ 
    private: 
    player *P; 
    public: 
    game(); 
    // other stuff ... 
} 
3

gameクラスのメンバである必要がありP

現在、ここにあなたのコンストラクタで:

game::game(){ 
    player* P; 
    P = new player; 
}; 

PはCTORにローカルであるとすぐに、この関数が終了すると消えます。

ソリューション

Pgameのメンバーを作成します。

class game { 
private: 
    player * P; 
public: 

    game(); 
    ~game(); // NOTE: I have added a destructor 
    void playerStuff(); 
} 

そしてコンストラクタを変更:デストラクタでそれを削除するには、もちろんの

game::game(){ 
    P = new player; 
}; 

思い出し、:

game::~Game(){ 
    delete P; 
}; 

もちろん、<player.h>が含まれているため、このオブジェクトをヒープに割り当てる必要はなく、代わりにスタックを使用することができ、デストラクタでdelete Pの必要性が否定されます。

EDIT:

#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