中国民工

顽石-滚过的路总该留下痕迹

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=运算赋重载函数。

示例代码下载。

posted on 2007-11-20 15:26 中国民工 阅读(10341) 评论(0)  编辑 收藏 引用 所属分类: MFC


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理