2015-12-02 47 views
2

下面的代码正确编译在ideone(C++ 14,link):的std ::私人嵌套结构的阵列不能被初始化(错误C2248)

#include <iostream> 
#include <array> 
#include <vector> 

class Foo { 
public: 
    void foo() { auto stashedCells = cells; } 
private: 
    struct Bar { std::vector<int> choices; }; 
    std::array<Bar, 10> cells; 
}; 

int main() { 
    Foo foo; 
    foo.foo(); 
} 

然而,在Visual Studio 2015 ,它产生以下错误:

1> main.cpp 
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\array(220): error C2248: 'Foo::Bar': cannot access private struct declared in class 'Foo' 
1> c:\users\alcedine\documents\visual studio 2015\projects\mvce\mvce\main.cpp(9): note: see declaration of 'Foo::Bar' 
1> c:\users\alcedine\documents\visual studio 2015\projects\mvce\mvce\main.cpp(5): note: see declaration of 'Foo' 
1> c:\program files (x86)\microsoft visual studio 14.0\vc\include\array(220): note: This diagnostic occurred in the compiler generated function 'std::array<Foo::Bar,10>::array(const std::array<Foo::Bar,10> &)' 

单位编译成功,如果Foo::Bar为空或只是包含int,所以它似乎并不是由于访问说明符,编译消息,尽管这种效果。

这是由于C++ 11和C++ 14之间的一些区别? Visual Studio在这里的行为是否正确?

+0

编译细跟GCC 4.8.2用'--std = C++ 11''标志。 –

+0

@SashaPachev同样,使用'--std = C++ 11'和'--std = C++ 14'标志编译GCC 5.2.0。 –

+0

看起来像一个错误。用\t'的std ::矢量细胞{10}更换阵列;' 效果很好。 – Christophe

回答

2

这似乎是MSVC2015的一个bug。

的问题是有关您在foo()使阵列的复制建设。它看起来与std::array的执行没有直接关系,因为boost::array产生完全相同的错误。

一种解决方法是从复制拆分结构,例如:

void foo() 
{ 
    decltype(cells) stashedCells; // this works 
    stashedCells = cells;   // this works 
} 

或者:

void foo() 
{ 
    std::array<Bar, 10> stashedCells; 
    stashedCells = cells; 
} 

其它可能的解决方法,例如使用公众typedef或类型别名阵列和/或Bar总是失败。该错误仅在公开Bar时消失。