【问题标题】:Concurrency::critical_section build error: cannot access private memberConcurrency::critical_section 构建错误:无法访问私有成员
【发布时间】:2014-08-21 09:06:55
【问题描述】:

我无法在代码(vs2013)块下构建并出现错误“错误 C2248:'Concurrency::critical_section::critical_section':无法访问在类 'Concurrency::critical_section' 中声明的私有成员” em>

任何人都可以帮助解释为什么会发生这种情况?谢谢

#include <ppl.h>

class Class1{

public: 

    concurrency::critical_section _cs;
    int f1;
    Class1(int f){ f1 = f; }
};

class Class2{

public: 
    std::vector<Class1> v1;
    Class2(){ v1.push_back(Class1(1)); v1.push_back(Class1(2)); }
};

int _tmain(int argc, _TCHAR* argv[])
{    
    Class2 c2();

    return 0;
}

【问题讨论】:

  • 您收到的错误信息是all吗?请编辑您的问题以包含 completeunedited 错误日志。另外请指出错误在代码中的哪一行。
  • concurrency::critical_section 不可复制。
  • Class2 c2(); 没有声明对象c2。它将其声明为返回 Class2 的函数
  • @Ajay。修改为Class2 c2;谢谢。错误仍然存​​在。
  • @Xin 供以后参考,VS的“错误列表”中的错误信息一般都是不完整的。您需要检查构建输出以获取完整消息。

标签: c++ ppl concurrency-runtime


【解决方案1】:

concurrency::critical_section 既不可复制也不可移动(这是以老式的方式制作其复制构造函数private,因此会出现错误)。因此,写的Class1也不能复制或移动,也不能将push_back放入向量中。

要解决此问题,您可以编写自己的复制构造函数和复制赋值运算符,仅复制 f1

class Class1
{
public: 
        concurrency::critical_section _cs;
        int f1;
        Class1(int f) : f1(f) { }
        Class1(const Class1 &other) : f1(other.f1) { }
        Class1 & operator=(const Class1 &other) { 
            // synchronization omitted
            f1 = other.f1;
        }
};

旁注:Class2 c2(); 声明了一个返回 Class2 的函数,而不是值初始化的对象。

旁注2:VS的“错误列表”中的错误信息通常不完整。您需要检查构建输出以获取完整的错误日志。在这种情况下,我的 VS2013 上的完整错误日志是:

ConsoleApplication2.cpp(15): error C2248: 'Concurrency::critical_section::critical_section' : cannot access private member declared in class 'Concurrency::critical_section'
          D:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\concrt.h(3712) : see declaration of 'Concurrency::critical_section::critical_section'
          D:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\concrt.h(3549) : see declaration of 'Concurrency::critical_section'
          This diagnostic occurred in the compiler generated function 'Class1::Class1(const Class1 &)'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 2014-01-10
    • 2023-03-22
    • 2013-04-02
    • 2012-05-13
    相关资源
    最近更新 更多