(我已阅读此处发布的所有帖子和谷歌,我无法解决此问题)
编译时,我遇到了不完整的类型错误。我设计项目的方式,游戏指针是不可避免的。
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.
答案 0 :(得分:2)
让我们回顾一下错误:
1)在main
中,这是一个错误:
game.gamePtr->map->test();
gamePtr
和map
是private
Game
成员,因此无法访问。
2)Map
缺少在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
的成员并将其移至public
类中的Game
,以便main()
可以成功编译。
答案 1 :(得分:0)
您需要使用前向声明。在类Game的定义之前放置Map类的声明:
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();
};
答案 2 :(得分:0)
您使用Map
和Game
类的每个地方都可以通过创建它的实例或通过 - >取消引用指向它的指针或*你必须使那种类型“完整”。这意味着main.cpp
必须包含map.h
,map.cpp
必须直接或间接包含game.h
。
请注意,您向前声明class Game
以避免game.h
包含map.h
,这是正确的,但map.cpp
必须包含game.h
当你取消引用指向类Game
的指针时。