关于嵌套类访问外围类私有成员的问题

ck_chuyun 2003-08-20 03:28:09

class List
{
public:

private:
static const int a = 3;
enum ListStatus{ Good, Empty, Corrupted };

class ListItem
{
public:
const char cc[a];
ListStatus status;
ListItem( int val = 0 );
void tt(){ List::a; } // a虽然是静态,但它是私有的!!!
};
};

在List没有把ListItem声明为友元的情况下,应该不可以访问List的私有成员(不管
其类型是不是静态的!!!) 可我在void tt()中使用List::a为什么能通过呢?
...全文
172 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Flamesong 2003-08-22
  • 打赏
  • 举报
回复
这些都是人为规定的就像楼上所说“应该和编译器的实现有关”。
nirvana_li 2003-08-22
  • 打赏
  • 举报
回复
应该和编译器的实现有关……
ck_chuyun 2003-08-22
  • 打赏
  • 举报
回复
昨天晚上我忽然想到了原因! 在Dev C++ 4.9.8.1中通过!

class List
{
static const int a = 3;
enum ListStatus{ Good, Empty, Corrupted };

class ListItem
{
public:
void tt()
{
// 为什么能找到a
int b = a;
ListStatus z = Good;
}
private:
enum ctx{ first, second };
static const int tw = 5;
};

// 无法找到ctx与tw的声明
ctx xs;
void pp(){ int temp = tw; }

};



1、为什么在tt()函数里的b能够访问外围类的私有成员a ?
由于在嵌套类ListItem里没有找到a的声明,所以在外围类寻找,因此找到了a。

2、为什么外围类的ctx和pp()函数里的tw没有被找到 ?
由于在嵌套类ListItem里没有把List声明为友元,所以名字解析时无法在ListItem中寻找声明。
当List被声明友元后,编译器还是不会主动进入ListItem里寻找声明,所以需要用类域来指名声明
所在的位置
ListItem::ctx
ListItem::tw // 去掉ListItem::限定修饰符,依旧就会找不到tw和ctx!!!

另外,只有当成员为静态、枚举或类型名时(公有私有都不会影响),上述访问才成立!

下面是改过后的代码,可以通过运行!

class List
{
static const int a = 3;
enum ListStatus{ Good, Empty, Corrupted };

class ListItem
{
// 加上了友元声明
friend class List;
public:
void tt()
{
int b = a;
ListStatus z = Good;
}
private:
enum ctx{ first, second };
static const int tw = 5;
};

// 使用了限定修饰符
ListItem::ctx xs;
void pp(){ int temp = ListItem::tw; }

};
ck_chuyun 2003-08-20
  • 打赏
  • 举报
回复
狂晕啊
ck_chuyun 2003-08-20
  • 打赏
  • 举报
回复
我用的是Dev C++ 4.9.8.1
和VC7.0
  • 打赏
  • 举报
回复
你用的什么编译器?我用VC6.0会报错哦:)
G:\MyProjects\rubbish01\rubbish.cpp(679) : error C2248: 'a' : cannot access private member declared in class 'List'

class List
{
public:

private:
static const int a ;
enum ListStatus{ Good, Empty, Corrupted };

class ListItem
{
public:
//const char cc[a];
ListStatus status;
ListItem( int val = 0 );
void tt(){ List::a; } // a虽然是静态,但它是私有的!!!
};
};
const int List::a=3;
ck_chuyun 2003-08-20
  • 打赏
  • 举报
回复
const char cc[a];
ListStatus status;

这二个可以解析出来,但函数内的却是调用,按C++的规定,访问私有成员必需是友元或成员函数啊
sevecol 2003-08-20
  • 打赏
  • 举报
回复
Nested classes can directly use names, type names, names of static members, and enumerators only from the enclosing class. To use names of other class members, you must use pointers, references, or object names.

64,281

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧