我应该对嵌套类使用朋友功能吗 [英] Should I use friend function for nested classes

查看:77
本文介绍了我应该对嵌套类使用朋友功能吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

在其中一本著名的书《 C ++中的思维》中,布鲁斯·埃克尔(Bruce Eckel)举例说明了嵌套类是像朋友一样的

Hi All,

In one of the famous book called Thinking in C++, in one of the example Bruce Eckel made nested class as friend like,

class upper
{
private:
int i;

class nested;// forward declaration  

friend nested;

class nested
{
public:
uppder obj;
void SomeFunction()
{
cout<< obj.i; 
}
};

};



我使用了上面的代码而不使用嵌套类的朋友,并且可以正常工作.那么结论是什么,嵌套类应该被声明为访问外部类私有数据的朋友,还是可以直接使用它而无需 friend 关键字.



I used above code without using friend to nested class and worked correctly. So what should be the conclusion, does nested class should be declared as friend for accessing private data of outer class or it can directly access it without friend keyword.

推荐答案

很长一段时间后,本节中的一个好问题.

Pranit,Bruce Eckel给出了此声明,因为它基于1998 C ++草案是正确的.现在,如果您使用的是任何编译器,请说MSVC 6.0,那么,如果您未将嵌套类的朋友类设为
,则会收到错误消息.

但是,后来的草案对此进行了更正,并指出
嵌套类是成员,因此具有与任何其他成员相同的访问权限",
因此,如果您使用此修改随附的任何编译器,则不再需要使用"friend"
A nice question in this section after long time.

Pranit, Bruce Eckel gave this statement as it is true based on the 1998 C++ draft. Now if you are using any compiler say MSVC 6.0 then you will get error if you haven''t made your nested class friend class.

However a latter draft corrected this and stated that
"A nested class is a member and as such has the same access rights as any other member",
so if you use any compiler shipped with this modification then the use of ''friend'' is no longer needed


这篇关于我应该对嵌套类使用朋友功能吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆