c++ - 使用带有虚函数的类的构造函数进行大括号初始化

标签 c++ c++11 initialization aggregate list-initialization

我知道聚合不能有虚拟成员函数,但此代码可以编译

struct B {
    B(int yIn) :y(yIn) {}
    int y;
    virtual void f() {}
};

B b = {3}; 

大括号初始化与聚合初始化不同,还是该类因其构造函数而成为有效聚合?

最佳答案

是的B不是aggregate type ,它不能有虚拟成员函数。因此 B b = {3}; 将不会执行 aggregate initialization ,但是copy-list-initialization (since C++11)相反,结果是调用构造函数 B::B(int) 来初始化对象。

  • Otherwise, the constructors of T are considered, in two phases:

    • ...

    • If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all).

关于c++ - 使用带有虚函数的类的构造函数进行大括号初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62497502/

相关文章:

c++ - 如何传递用户数据来比较 std::sort 的功能?

具有右值引用的 C++ 构造函数

ruby-on-rails - Stripe Live 可发布 API key 不正确

c++ - 为什么变量 “sum”必须在函数中而不是在main之外初始化?

c++ - Iterator<T> 来自 istream,无格式提取

c++ - 在不同优化级别访问 gcc/g++ 中的局部变量和全局变量的速度

c++ - 模板化函数时链接器错误未找到析构函数

c++ - 允许使用右值的地址吗?

swift - 枚举类的初始化和将TemperatureUnit.Kelvin分配给self(self = .Kelvin)的困惑

c++ - 不用 cmath 计算 sin