如何传递当前类引用以在 C++ 中初始化类成员
how to pass the current class reference to initialize class members in c++
我的类A
有一个类 B 的对象数组作为成员,要求是在类 A 的构造函数中,我需要将this
传递给数组中的每个B
对象。但是,尝试在 A
的构造函数主体中循环它们不起作用:
for (i=0;i<max(B_obj);i++) {
B_obj[i](this);
}
工作代码示例
struct A : EventHandler {
A() : B_obj_1(this) {}
B B_obj_1;
};
代码示例 不工作
struct A : EventHandler {
A() : {
for (auto i = 0; i<4; i++) {
B_obj[i](this);
}
}
B B_obj[5];
};
如果你B
的唯一构造函数是B(A*)
(没有无参数的(,那么你必须使用成员列表初始化:
A() : b_obj{{this}, {this}, {this}, {this}, {this}} {}
不过,这很快就会变得混乱,因此更好的解决方案是使用 std::vector
或创建一个无参数构造函数,然后稍后复制初始化它们。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 在C和C++中初始化结构中的数组
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 在函数内部的声明中初始化数组,并在外部使用它
- 继承:构造函数,初始化C++11中基类的类C数组成员