带虚拟函数的类的大括号初始化 [英] Brace initialization for class with virtual function

查看:213
本文介绍了带虚拟函数的类的大括号初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这个代码:

  struct A {
int x;
void f(){}
};

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

A a = {2};

// B b = {3};错误:没有匹配的构造函数初始化'B'

int main(){
return 0;
}

为什么要初始化变量 a 工作但不适用于变量 b

解决方案

A 是一个聚合,因此可以有括号初始化, B 不是,因为它有一个虚方法。 p>

8.5.1汇总


数组或没有用户提供的构造函数(12.1)的类(第9条),非静态数据成员(9.2)没有括号或等于
初始化器,没有私有或受保护的非静态数据成员第11条),
没有基类(第10条),没有虚函数(10.3)。



There is this code:

struct A {
   int x;
   void f() {}
};

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

A a = {2};

//B b = {3}; error: no matching constructor for initialization of 'B'

int main() {
   return 0;
}

Why initialization for variable a works but not for variable b?

解决方案

A is an aggregate, and so can have brace initialization, and B isn't, since it has a virtual method.

8.5.1 Aggregates

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal- initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

这篇关于带虚拟函数的类的大括号初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆