gpt4 book ai didi

c++ - 如何在 C++ 中创建 "wrapper"?

转载 作者:太空狗 更新时间:2023-10-29 20:13:05 30 4
gpt4 key购买 nike

更新如下

我正在尝试创建此包装器以包含指向所有其他类的指针。我遇到了这个问题(示例):

主要.cpp

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

游戏.h

class Game {
private:
wrap* info;
}

有没有办法解决这个问题,wrap 需要 Game,而 Game 需要 wrap。 (我知道包装类 [this case struct] 不是最佳实践,但我在其他类中经常需要该信息。)

现在,我有一个新问题。

项目.h

// top
struct CoreInfo;


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

(结构 CoreInfo 包含一个变量“int testing”。我不知道如何访问 items 类中的任何内容,正常错误:7 request for member 'testing' in 'b',它是非类输入“CoreInfo*”

最佳答案

只需向前声明包装结构,如下所示:

主要.cpp

#include "game.h"

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

游戏.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;
}

酒吧.h

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

酒吧.cpp

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

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

关于c++ - 如何在 C++ 中创建 "wrapper"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23575247/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com