先看一段示例代碼:
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=運算賦重載函數。
示例代碼下載。