【问题标题】:Passing CList variable gives error C2248: 'CObject::CObject' : cannot access private member传递 CList 变量给出错误 C2248: 'CObject::CObject' : cannot access private member
【发布时间】:2015-01-26 17:00:54
【问题描述】:

在我的课堂上,我有一个静态的Clist variable,声明方式如下:

#include<stdio.h>
#include<conio.h>
#include <afxtempl.h>
void otherfunc(CList<int,int> a)
{

}
class A
{
public:
CList<int,int> myvariable;
void myfunc()
{
otherfunc(myvariable);
}

};


int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    a.myfunc();
    getch();
    return 0;
}

otherfunc() 不属于我的班级。

我哪里错了? 我刚刚粘贴了问题的代码 sn-p。我已经启动了它,除了我调用 otherfunc() 的行之外,所有文件都可以正常工作。它不依赖于静态关键字。即使我删除静态,我也会得到同样的错误。

已编辑:这是我得到的错误:

C:\program files (x86)\microsoft visual studio 9.0\vc\atlmfc\include\afxtempl.h(776) : error C2248: 'CObject::CObject' : cannot access private member declared in class 'CObject'
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\atlmfc\include\afx.h(561) : see declaration of 'CObject::CObject'
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\atlmfc\include\afx.h(532) : see declaration of 'CObject'
1>        This diagnostic occurred in the compiler generated function 'CList<TYPE,ARG_TYPE>::CList(const CList<TYPE,ARG_TYPE> &)'
1>        with
1>        [
1>            TYPE=int,
1>            ARG_TYPE=int
1>        ]

【问题讨论】:

    标签: c++ clist


    【解决方案1】:

    您的代码无法编译(Class 应该是 classPublic 应该是 public 等)。错误信息是什么?此外,您必须发布一个简单的可编译示例来重现您的错误。我的猜测是您没有在其类声明之外实例化您的静态变量,请参阅

    http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

    【讨论】:

    • @230490 请至少发布完整的错误消息/代码,否则我们只能猜测发生了什么。在您的代码 sn-p 中,没有私有变量。
    • 我创建了一个示例,可以将其复制粘贴到项目中以重现我面临的错误
    • @230490 你在上面的 sn-p 中打电话给otherfunc 哪里?
    • 在 myfunc() 中。我错过了删除评论部分
    • @230490 是 CList 可复制吗?即,CList 是否有复制构造函数?如果不是,则不能在otherfunc(Clist&lt;int, int&gt; a) 中按值传递,而需要通过引用otherfunc(Clist&lt;int, int&gt;&amp; a) 来传递CList,因为按值传递会调用复制构造函数。
    【解决方案2】:

    您可能不会因为“Public:”而收到错误消息。因为“Public:”不是关键词,而是标签。这就是为什么“myvariable”默认是私有的。 代替“公共:”使用“公共:”并将“静态”替换为静态。

    【讨论】:

      【解决方案3】:

      看一下-的定义

      void otherfunc(CList<int,int> a)
      

      输入参数CList&lt;int,int&gt; a是按值传递的,也就是说当你调用这个函数时,它会使用CList&lt;int,int&gt;复制构造函数来复制输入参数。
      但是CList&lt;int,int&gt; 没有实现 Copy Constructor,其基类 CObject 将其 Copy Constructor 定义为私有。

      您应该将定义更改为 -

      void otherfunc(CList<int,int>& a)
      
      猜你喜欢
      • 2011-09-06
      • 2015-05-05
      • 2013-08-17
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 2017-02-19
      • 2021-05-13
      相关资源
      最近更新 更多