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