c++ - 私有(private)嵌套结构的 std::array 无法初始化(错误 C2248)

标签 c++ visual-studio-2015

以下代码在 ideone 中可以正确编译(C++14,link):

#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 在这里表现正常吗?

最佳答案

这似乎是 MSVC2015 的一个错误。

问题与您在 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;
}

其他潜在的解决方法,例如使用公共(public) typedef 或数组和/或 Bar 的类型别名,总是会失败。仅当将 Bar 公开时,该错误才会消失。

关于c++ - 私有(private)嵌套结构的 std::array 无法初始化(错误 C2248),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34052576/

相关文章:

c++ - 无法与标准库链接

asp.net - IIS Express localhost 对于第一个请求加载速度非常慢

c++ - 您使用什么调试器工具来查看 STL 容器的内容(在 Linux 上)

c++ - Eclipse CDT条件编译?

c++ - 在 C++ 中拆分和合并 std::list

visual-studio - 在 Visual Studio 中启动 DotNetNuke 项目的正确方法是什么?

c++ - 具有前向声明类型的函数模板特化

c++ - OpenGL在GPU上构建和使用数据

c++ - 函数模板参数推导是否应该考虑转换运算符?

visual-studio-2015 - 插入符在 Visual Studio 2015 中的错误位置