gpt4 book ai didi

具有聚合初始化的 C++11 构造函数委托(delegate)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:47:05 26 4
gpt4 key购买 nike

是否可以在我自己定义的默认构造函数中调用聚合初始化?

GCC 使用以下代码提示“错误:构造函数委托(delegate)给自身”:

struct X {
int x, y, z, p, q, r;
X(): x{}, y{}, z{}, p{}, q{}, r{} { } // cumbersome
//X(): X{} { } // the idea is nice but doesn't compile
};

我目前在 ctor 主体中使用 memset(this, 0, sizeof(*this))

最佳答案

一种方法是通过以下方式欺骗重载决议:

struct X {
int x, y, z, p, q, r;
X(int) : x{}, y{}, z{}, p{}, q{}, r{} { }
X() : X(0) { }
};

另一种方法是使用类内默认成员初始化:

struct X {
int x = 0, y = 0, z = 0, p = 0, q = 0, r = 0;
};

在您的具体示例中,您还可以:

struct X {
std::array<int, 6> vars{};
};

关于具有聚合初始化的 C++11 构造函数委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37593140/

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