大括号用虚函数初始化结构

Brace Initialize struct with virtual functions

Brace initialization

        struct A
        {
            int a;
            int b;
            void foo(){}
        };

        A a{1, 2};

它工作正常。但是如果把foo改成虚函数,编译不会报错,

Error C2440 'initializing': cannot convert from 'initializer list' to

我发现 ,

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

但这背后的原因是什么?

为什么不使用带参数的构造函数 virtual void foo() {}

struct A
{
    int a;
    int b;
    A(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    virtual void foo() {}
};
A a{ 1, 2 }; 

没有办法。就像你提到的这篇文章

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

这意味着 class/struct 或具有

的数组
  • 没有user-provided个构造函数
  • 没有私有或受保护的 non-static 数据成员
  • 没有基础类
  • 并且没有虚函数

是一个集合。并且只有聚合可以进行大括号初始化。所以在这种情况下,你的结构有一个虚函数,它违反了上述其中一条定律,并使其成为 non-aggregate.

不知道为什么会这样

我想如果你的结构类似于 c 中的结构那么你的结构就可以工作。

就像 Hassan 的 一样,您应该改用参数化构造函数。