简体   繁体   English

如何在C ++中创建“包装器”?

[英]How to create a “wrapper” in C++?

Update Below 在下面更新

I am trying to create this wrapper to contain pointers to all the other classes. 我正在尝试创建此包装器以包含指向所有其他类的指针。 I've hit this issue (example): 我遇到了这个问题(例子):

main.cpp main.cpp中

struct wrap {
  Game* game;
  Player* player;
  Map* map;
};

game.h game.h

class Game {
  private:
    wrap* info;
}

Is there a way around this, wrap needs Game, and Game needs wrap. 有没有解决方法,包装需要游戏,游戏需要包装。 (I do know wrapper class [this case struct] is not the best practice, but I am needing that info frequently in other classes.) (我知道包装类[此案例结构]不是最佳实践,但我在其他类中经常需要该信息。)

Now, I have a new problem. 现在,我有一个新问题。

items.h items.h

// top
struct CoreInfo;


void Items::test() {
    struct CoreInfo* b;
    //b->testing = 4;
}

(The struct CoreInfo contains a variable "int testing." And I cannot figure out how to access anything within the items class, normal error: 7 request for member 'testing' in 'b', which is of non-class type 'CoreInfo*' (结构CoreInfo包含一个变量“int testing”。我无法弄清楚如何访问items类中的任何内容,正常错误:7请求'b'中的成员'testing',这是非类型的'CoreInfo' *”

just forward declare the wrap struct, as shown below: 只需向前声明wrap结构,如下所示:

main.cpp main.cpp中

#include "game.h"

struct wrap {
  Game* game;
  Player* player;
  Map* map;
};

game.h game.h

struct wrap;

class Game {
  private:
    struct wrap* info;
}

edit: 编辑:

the problem is that you did not make a separation between declaration and definition by taking advantage of compilation units. 问题是你没有利用编译单元在声明定义之间进行分离。 If you define your class and its members in a compilation unit ( items.cpp ), while declaring it in the header items.h , you'll have no trouble. 如果你在编译单元( items.cpp )中定义你的类及其成员,在标题items.h 声明它,你就没有问题。

Let's make an example to illustrate this: 让我们举一个例子来说明这一点:

foo.h foo.h中

#include "bar.h"

class A {
    B b_instance;
    void do_something(int i, int j);
}

foo.cpp Foo.cpp中

#include "foo.h"

int A::do_something(int i, int j) {
   return i+j; 
}

bar.h bar.h

class B {
    A a_instance;
    void use_a();
}

bar.cpp bar.cpp

#include "foo.h" // which includes bar.h as well

void B::use_a() {
    int k = a_instance.do_something();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM