c++ - 我可以存储指向转发声明的类/结构的指针吗?
问题描述
#include <stdio.h>
struct B;
struct A {
B* b;
int num = 4;
A() {
b = new B(this);
}
};
struct A;
struct B {
A* a;
int num = 21;
B(A* a) {
this->a = a;
}
// function that does stuff with both A and B nums
int add() {
return num + a->num;
}
};
int main()
{
A thing;
printf("%d",thing.b->add());
return 0;
}
所以我的代码中有两个结构,其中 structB
是 struct 的成员A
。我只是希望他们存储彼此的指针,以便他们可以访问彼此的成员变量。这甚至可能吗?我愿意接受重构建议。
解决方案
这是可能的,但您将不得不移动一些代码,因为在完全知道类型之前无法编译许多表达式。例如,在完全知道new B(this)
之前无法编译。B
所以A
构造函数需要在B
定义后编译,像这样
struct B;
struct A {
B* b;
int num = 4;
A();
};
struct B {
A* a;
int num = 21;
B(A* a) {
this->a = a;
}
// function that does stuff with both A and B nums
int add() {
return num + a->num;
}
};
inline A::A() {
b = new B(this);
}
int main()
{
A thing;
printf("%d",thing.b->add());
return 0;
}
推荐阅读
- python - 如何使用时间在 datetimeIndex 数组中进行索引
- php - 404 未找到;Apache Server 无法加载简单的 php 文件
- arrays - 使用数组将文本从一个工作表传递到另一个工作表
- python - 协助 Python 函数
- react-native - 反应本机和 fblogin - ld:找不到 -lBolts 的库
- angular - 如何从 Angular 的 PrimeNG 库中为 AutoComplete 组件设置焦点
- r - 在 R 中,如何定义模型对比以比较两个条件相对于一个公共控件?
- webpack - mini-css-extract-plugin TypeError:无法匹配“未定义”或“空”
- ruby-on-rails - Rails/Sidekiq:帮助我理解这个 `initializers/sidekiq.rb` 示例中的重复
- android - 色调属性导致矢量图形上的像素化