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
应该按照标准进行这项工作,还是这实际上是非法的?我滥用类内初始值设定项吗?我认为新的语法会使它成为可能,所以我不必为了初始化而编写构造函数,但是现在看来,我可能不得不使用旧的机制来避免未初始化结构的可能性。
我相信这会改变C++ 14。 –