如何传递当前类引用以在 C++ 中初始化类成员

how to pass the current class reference to initialize class members in c++

本文关键字:C++ 初始化 成员 引用 何传递      更新时间:2023-10-16

我的类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 或创建一个无参数构造函数,然后稍后复制初始化它们。