嵌套类对包含类的私有数据成员的访问 [英] Nested class' access to enclosing class' private data members

查看:369
本文介绍了嵌套类对包含类的私有数据成员的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在实现嵌套类时遇到问题,其构造函数使用某些封闭类的私有数据成员初始化。

I'm having trouble implementing a nested class who's constructor is initialized with some of the enclosing class' private data members.

示例:

Header File:
class Enclosing {
   //...Public members
   //...Private members
   int x, int y
   class Inner; // Declaration for nested class
};

Impl. File:
// Stuff...
class Enclosing::Inner {
    explicit Inner() : foo(x), bar(y) // foo and bar are data members of Inner
    //...
};

我得到一个无效的非静态数据成员错误。

推荐答案

成员 x y Enclosing 的非静态数据成员它们只存在于 Enclosing 类的具体对象中。没有具体的对象, x y 都存在。同时,你试图引用 x y ,没有对象。

Member x and y are non-static data member of Enclosing, which means that they only exist within a concrete object of Enclosing class. Without a concrete object, neither x nor y exist. Meanwhile, you are trying to refer to x and y without an object. That can't be done, which is what the compiler is trying to tell you.

如果你想初始化成员 Inner :: foo Inner :: bar x y ,你必须将 Enclosing 类型的具体对象传递给 Inner 的构造函数。例如

If you want to initialize members Inner::foo and Inner::bar from x and y, you have to pass a concrete object of Enclosing type into the Inners constructor. For example

class Enclosing::Inner {    
  explicit Inner(const Enclosing& e) : foo(e.x), bar(e.y) 
    {}
  //...
};

额外的注意:在原来的C ++ 98内部类没有特殊的权限访问外部类。使用C ++ 98编译器,你必须给内部类必要的权限(友谊)或暴露成员 x y 为公开。但是,这种情况在C +中被归类为缺陷, +98,并且决定内部类应该具有对外部类成员(甚至是私有成员)的完全访问权。因此,您是否必须对访问权限做任何额外的工作,取决于您的编译器。

Extra note: in the original C++98 the inner class has no special privileges is accessing the outer class. With C++98 compiler you'd either have to give the inner class the necessary privileges (friendship) or expose the members x and y as public. However, this situation was classified as a defect in C++98, and it was decided that inner classes should have full access to outer class members (even private ones). So, whether you have to do anything extra with regard to access privileges depends on your compiler.

这篇关于嵌套类对包含类的私有数据成员的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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