在下面更新
我正在尝试创建此包装器以包含指向所有其他类的指针.我遇到了这个问题(例子):
main.cpp中
struct wrap {
Game* game;
Player* player;
Map* map;
};
Run Code Online (Sandbox Code Playgroud)
game.h
class Game {
private:
wrap* info;
}
Run Code Online (Sandbox Code Playgroud)
有没有解决方法,包装需要游戏,游戏需要包装.(我知道包装类[此案例结构]不是最佳实践,但我在其他类中经常需要该信息.)
立即更新,我遇到了一个新问题.
items.h
// top
struct CoreInfo;
void Items::test() {
struct CoreInfo* b;
//b->testing = 4;
}
Run Code Online (Sandbox Code Playgroud)
(结构CoreInfo包含一个变量"int testing.",我无法弄清楚如何访问items类中的任何内容,正常错误:7请求'b'中的成员'testing',这是非类型的'CoreInfo'*"
只需向前声明wrap结构,如下所示:
main.cpp中
#include "game.h"
struct wrap {
Game* game;
Player* player;
Map* map;
};
Run Code Online (Sandbox Code Playgroud)
game.h
struct wrap;
class Game {
private:
struct wrap* info;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
问题是你没有利用编译单元在声明和定义之间进行分离.如果你在编译单元()中定义你的类及其成员,在标题中声明它,你就没有问题.items.cppitems.h
让我们举一个例子来说明这一点:
foo.h中
#include "bar.h"
class A {
B b_instance;
void do_something(int i, int j);
}
Run Code Online (Sandbox Code Playgroud)
Foo.cpp中
#include "foo.h"
int A::do_something(int i, int j) {
return i+j;
}
Run Code Online (Sandbox Code Playgroud)
bar.h
class B {
A a_instance;
void use_a();
}
Run Code Online (Sandbox Code Playgroud)
bar.cpp
#include "foo.h" // which includes bar.h as well
void B::use_a() {
int k = a_instance.do_something();
}
Run Code Online (Sandbox Code Playgroud)