2

If I uncomment the line testfn causes a compile error. What constructor can I add using =default to allow me to define the comment out lane and still use TestFn()? Remember t{a} should also work (not shown below).

struct Test2 {
    int a; int*p;
    Test2()=default;
    //Test2(int a, int b, int c){};
};
void TestFn() { Test2 t{5,nullptr}; }
4

1 回答 1

5

如果您明确定义Test2() {}.

这种形式的初始化称为聚合初始化,它仅适用于没有用户定义的构造函数的情况。它不通过任何构造函数,而是直接从花括号初始化列表中初始化成员。所以没有什么可以默认的;您必须明确定义所需的任何构造函数。

实际上,我对显式默认构造函数没有禁用聚合初始化感到有点惊讶。根据@juachopanza 的说法,C++11 的具体措辞是聚合初始化不依赖于定义,特别允许声明。

于 2013-09-11T06:34:40.447 回答