1

我在初始化使用类内初始化程序的结构时遇到问题:

struct A
{
    int a{};
    int b{};
};

struct B
{
    int a;
    int b;
};

int main()
{
    A a;    // OK
    B b{1, 2}; // OK
    B b2; // OK, but b.a and b.b are undefined
    A a2{1, 2}; // ERROR!
}

这是我从 gcc 4.7.2 得到的错误:

% g++ -std=c++11 test2.cc
test2.cc: In function ‘int main()’:
test2.cc:16:11: error: no matching function for call to ‘A::A(<brace-enclosed initializer list>)’
test2.cc:16:11: note: candidates are:
test2.cc:1:8: note: constexpr A::A()
test2.cc:1:8: note:   candidate expects 0 arguments, 2 provided
test2.cc:1:8: note: constexpr A::A(const A&)
test2.cc:1:8: note:   candidate expects 1 argument, 2 provided
test2.cc:1:8: note: constexpr A::A(A&&)
test2.cc:1:8: note:   candidate expects 1 argument, 2 provided

这应该按照标准工作,还是实际上是非法的?我是否滥用了类内初始化器的使用?我认为新语法会成功,所以我不必编写构造函数来进行初始化,但现在看来我可能不得不求助于旧机制来避免未初始化结构的可能性。

4

1 回答 1

3

您只能在以下情况下使用大括号

  • 大括号内容匹配构造函数(不是你的情况),或者

  • 该类是一个聚合,每个大括号元素都匹配一个类成员。

但是,如果 (C++11, 8.5.1/1),一个类是一个聚合:

它没有用于非静态成员的大括号或相等初始化器

你的班级显然有。所以,你也没有聚合。

要么编写合适的构造函数,要么删除大括号或相等初始化器。

于 2013-05-28T15:16:09.380 回答