[英]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();
gamePtr
和map
是Game
的private
成员,因此无法访问它们。
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();
};
通过创建Map
和Game
类的实例或通过->或*取消引用它的指针来使用Map
和Game
类的每个地方,都必须使该类型为“ complete”。 这意味着main.cpp
必须直接或间接包含map.h
而map.cpp
必须包括game.h
请注意,为了避免将game.h
包含在map.h
,您可以game.h
声明class Game
,这是正常的,但是map.cpp
必须包含game.h
因为您要在其中取消引用Game
类的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.