C++不完整类型错误

C++ Incomplete Type Error

本文关键字:类型 错误 C++      更新时间:2023-10-16

(我已经阅读了这里和谷歌上发布的所有线程,我无法从中修复)

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

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*的构造函数。

    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的用法,这是您最初发布的代码所没有的。我还在Game类中放置了private的成员,并将它们移动到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类的每个地方,通过->或*创建它的实例或取消引用指向它的指针,都必须使该类型"完整"。意味着main.cpp必须包含map.hmap.cpp必须直接或间接包含game.h

请注意,您正向声明class Game是为了避免game.hmap.h包含,这很好,但map.cpp必须包含game.h,因为您在那里取消引用指向类Game的指针。