如何传递当前类引用来初始化c ++中的类成员

时间:2018-03-14 13:46:42

标签: c++

我的类A有一个B类对象数组作为成员,要求是在类AI的构造函数中需要将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;

};

代码示例Notworking

struct A : EventHandler {
    A() : {
        for (auto i = 0; i<4; i++) {
            B_obj[i](this);
        }
    }
    B B_obj[5];
};

1 个答案:

答案 0 :(得分:1)

如果B(A*)的唯一构造函数是A() : b_obj{{this}, {this}, {this}, {this}, {this}} {} (没有无参数的),那么你必须使用成员列表初始化:

std::vector

这会变得很乱,所以更好的解决方案是使用purrr或创建无参数构造函数,然后稍后复制初始化它们。