松鼠的博客

导航

统计

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   Xproer-松鼠  阅读(1776)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示