繁体   English   中英

C ++不完整类型错误

[英]C++ Incomplete Type Error

(我已经阅读了所有在此发布的帖子以及google,无法对此进行修复)

我在编译时遇到不完整的类型错误。 在我设计项目的方式中,游戏指针是不可避免的。

main.cpp
#include "game.h"
// I actually declare game as a global, and hand itself its pointer (had trouble doing it with "this")
Game game;
Game* gamePtr = &game;
game.init(gamePtr);
game.gamePtr->map->test(); // error here, I also tested the basic test in all other parts of code, always incomplete type.


game.h
#include "map.h"
class Map;

class Game {

    private:
        Map *map;
        Game* gamePtr;

    public:
        void init(Game* ownPtr);
        int getTestInt();
};


game.cpp
#include "game.h"

void Game::init(Game* ownPtr) {
    gamePtr = ownPtr;
    map = new Map(gamePtr); // acts as "parent" to refer back (is needed.)
}

int Game::getTestInt() {
    return 5;    
}


map.h
class Game;

class Map {
    private:
        Game* gamePtr;
    public:
        int test();
};

map.cpp 
#include "map.h"

int Map::test() {
    return gamePtr->getTestInt();
}

// returns that class Game is an incomplete type, and cannot figure out how to fix.

让我们回顾一下错误:

1)在main ,这是一个错误:

    game.gamePtr->map->test(); 

gamePtrmapGameprivate成员,因此无法访问它们。

2) Map缺少在Game.cpp中采用Game*Game.cpp

    map = new Map(gamePtr); 

这是一个完整的可编译示例。 您必须提供缺少主体的功能,例如Map(Game*)

game.h

#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED

class Map;
class Game {
    private:
        Map *map;
    public:
        Game* gamePtr;
        void init(Game* ownPtr);
        int getTestInt();
    };
#endif

game.cpp

#include "game.h"
#include "map.h"

void Game::init(Game* ownPtr) {
    gamePtr = ownPtr;
    map = new Map(gamePtr); // acts as "parent" to refer back (is needed.)
}

int Game::getTestInt() {
    return 5;    
}

map.h

#ifndef MAP_H_INCLUDED
#define MAP_H_INCLUDED

class Game;
class Map {
    private:
        Game* gamePtr;
    public:
        int test();
        Map(Game*);
};
#endif

map.cpp

#include "game.h"
#include "map.h"

int Map::test() {
    return gamePtr->getTestInt();
}

main.cpp

#include "game.h"
#include "map.h"

int main()
{
    Game game;
    Game* gamePtr = &game;
    game.init(gamePtr);
    game.gamePtr->map->test(); 
}

在完成此操作并在Visual Studio中创建项目后,构建应用程序没有任何错误。

请注意您最初发布的代码所没有的#include guards的用法。 我还把private成员放到Game类中,然后将它们移到public ,以便main()可以成功编译。

您需要使用前向声明。 将Map类的声明放在类Game的定义之前:

game.h

class Map; // this is forward declaration of class Map. Now you may have pointers of that type
class Game {

    private:
        Map *map;
        Game* gamePtr;

    public:
        void init(Game* ownPtr);
        int getTestInt();
};

通过创建MapGame类的实例或通过->或*取消引用它的指针来使用MapGame类的每个地方,都必须使该类型为“ complete”。 这意味着main.cpp必须直接或间接包含map.hmap.cpp必须包括game.h

请注意,为了避免将game.h包含在map.h ,您可以game.h声明class Game ,这是正常的,但是map.cpp必须包含game.h因为您要在其中取消引用Game类的指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM