我知道聚合不能有虚拟成员函数,但此代码可以编译
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/