嵌套类可以访问外围类的私有成员

来源:互联网 发布:淘宝女装春季服饰图片 编辑:程序博客网 时间:2024/04/26 11:21
看c++primer时读到一句话 ——

p800页关于nested class的,
listitem is not permitted to access a private data member of its enclosing class, such as list.

意思是说,内部类不能访问外部类的私有成员,但我自己做了实验,内部类是可以访问外部类的私有成员的.


最后翻看C++11标准,才知道问题的原因在于新版 C++ 标准对此有了不同的规定,具体见:
c++03 11.8/1
The members of a nested class have no special access to members of an enclosing class, nor to classes or functions that have granted friendship to an enclosing class; the usual access rules (clause 11) shall be obeyed. The members of an enclosing class have no special access to members of a nested class; the usual
access rules (clause 11) shall be obeyed.

c++11 11.7/1
A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules (Clause 11) shall be obeyed.

根据 c++11 11.7/1,我的代码是合法的。根据 c++03 11.8/1 和 c++ primer 成书的年代,Lippman 也是正确的。


代码:

#include <iostream>using namespace std;template<typename T>class A{public:A(const T& val):m_val(val){}private:class B{public:void print(const A& obj);};public:B* Get();private:B test;T m_val;};template<typename T>typename A<T>::B*  A<T>::Get(){return &test;}template<typename T>void A<T>::B::print(const A& obj){cout<<obj.m_val<<endl;}int main(){A<int>obj(2);obj.Get()->print(obj);return 0;}


#include <iostream>using namespace std;template<typename T>class A{public:A(const T& val);~A();private:class B;public:B* Get();private:B* m_pTest;T m_val;};                                                                                                template<typename T>class A<T>::B{public:void print(const A& obj);};                                                                                                          template<typename T>A<T>::A(const T& val):m_pTest(new B),m_val(val){}template<typename T>A<T>::~A(){delete m_pTest; m_pTest=NULL;}template<typename T>typename A<T>::B*  A<T>::Get(){return m_pTest;}template<typename T>void A<T>::B::print(const A& obj){cout<<obj.m_val<<endl;}int main(){A<int>obj(2);obj.Get()->print(obj);return 0;}


原创粉丝点击