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

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

问题描述

我在实现一个嵌套类时遇到问题,该类的构造函数是用一些封闭类的私有数据成员初始化的.

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
    //...
};

我收到一个非静态数据成员的无效使用错误.在嵌套类访问其封闭类的成员时,我是否遗漏了什么?

I get an invalid use of non-static data member error. Is there something I'm missing when it comes to nested class access to its enclosing class' members?

推荐答案

Member xyEnclosure 的非静态数据成员,这意味着它们只存在于 Enclosure 类的具体对象中.没有具体的对象,xy 都不存在.同时,您试图在没有对象的情况下引用 xy .这是不可能的,这就是编译器试图告诉你的.

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.

如果你想从 xy 初始化成员 Inner::fooInner::bar,您必须将 Enclosure 类型的具体对象传递给 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 编译器,您要么必须为内部类提供必要的特权(友谊),要么将成员 xy 公开为公共.但是,这种情况被归类为缺陷在 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天全站免登陆