error C2248: 'CObject::operator =' : cannot access private member declared in class 'CObject'

error C2248: 'CObject::operator =' : cannot access private member declared in class 'CObject'

先看一段示例代码:

 1  #define C2248_SWITCH    0
 2 
 3  struct A
 4  {
 5      int a;
 6  };
 7 
 8  struct B
 9  {
10      CArray < A , A& >  b;
11  #if C2248_SWITCH
12      const B& operator=(const B& rhs)
13      {
14          if(this !=  &rhs )
15          {
16              b.RemoveAll();
17              b.Append(rhs.b);
18              b.FreeExtra();
19          }
20 
21          return *this;
22      }
23  #endif
24  };
25 
26  typedef CArray < B , B& >  C;
27 
28  void test()
29  {
30      B b;
31      C c;
32      c.Add(b); // C2248, C2248_SWITCH is defined as 0.
33  }
34 

编译时产生如下信息:
 1  Compiling
 2  CArrayTest.cpp
 3  c:/program files/microsoft visual studio 8/vc/atlmfc/include/afxtempl.h(272) : error C2248: 'CObject::operator =' : cannot access private member declared in class 'CObject'
 4          c:/program files/microsoft visual studio 8/vc/atlmfc/include/afx.h(559) : see declaration of 'CObject::operator ='
 5          c:/program files/microsoft visual studio 8/vc/atlmfc/include/afx.h(529) : see declaration of 'CObject'
 6          This diagnostic occurred in the compiler generated function 'CArray < TYPE ,ARG_TYPE >   &CArray < TYPE ,ARG_TYPE > ::operator =(const CArray < TYPE ,ARG_TYPE >  &)'
 7          with
 8          [
 9              TYPE=A,
10              ARG_TYPE=A &
11          ]
从以上的编译信息line9, line10可以看出是struct B默认的operator=运算符函数(由编译器自动产生)出现了问题。因为struct B有一个CArray<A, A&>的成员变量,而CArray<A, A&>类的operator=是private类型(它继承自CObject::operator=,且被定义为private类型)。所以我们要在struct B中重载operator=运算符,且把它声明为public类型(struct中的成员变量和成员函数默认就是public类型,所以不用显式的指明public).

 

在本示例代码中,只需把C2248_SWITCH定义为1即可。 由本例可以看出,如果我们的类/结构体中有CArray(或CList等其他的派生自CObject类)的成员变量,我们最好添加上一个public类型的operator=运算赋重载函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值