gpt4 book ai didi

c++ - 为什么用大括号 init 初始化对象是合法的,即使它不是聚合?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:15:25 27 4
gpt4 key购买 nike

我不明白为什么允许变体 1。

class A {
public:
A(int x, int y) : a{x}, b{y} {}

private:
int a;
int b;
};

class B : public A {
public:
// Variant 1
//B(int x, int y, int z) : A{x,y}, c{z} {}

// Variant 2
B(int x, int y, int z) : A(x,y), c{z} {}
private:
int c;
};

int main() {
B b(1,2,3);
}

此代码是使用 -std=c++11 构建的。

  1. 变体 1 和 2 哪个更好,为什么?
  2. 此处:http://en.cppreference.com/w/cpp/language/aggregate_initialization它说要允许使用大括号 init,该类必须是聚合,而 A 不是。为什么这仍然可以编译?

最佳答案

Here: http://en.cppreference.com/w/cpp/language/aggregate_initialization it says that for brace init to be allowed, the class must be an aggregate, which A is not. Why does this still compile?

它还说:

Aggregate initialization is a form of list-initialization, which initializes aggregates

这不是您正确推测的聚合初始化。但是,它仍然被允许作为列表初始化。由于 C++11 大括号可用于初始化非聚合的事物。它根本不算作聚合初始化。

关于c++ - 为什么用大括号 init 初始化对象是合法的,即使它不是聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25486249/

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