C ++嵌套类,访问父类变量 [英] C++ nested classes, access fathers variables

查看:697
本文介绍了C ++嵌套类,访问父类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题已经说了很多,

但基本上我想做的是以下(示例):

but basically what i want to do is the following(Example):

我有一个类叫做A,另一个类在被调用的B里,像这样:

I have a class called A, and another class inside a called B, like so:

class A
{
   int a;

   class B
   {
      void test()
      {
         a = 20;
      }
   };
};

正如你所看到的,我的目标是让B类有权访问类A,因为它是一个嵌套类。

As you can see my goal is for class B to have access to class A, as it is a nested class. Not this wont work, because B doesn't have access to A, but how can it get access?

谢谢

推荐答案

尽管你在A中声明了B类,但是A类和B类仍然是完全独立的。唯一的区别是现在引用B,必须做A :: B。

Despite that you declared class B inside of A, classes A and B are still completely independent. The only difference is that now to refer to B, one must do A::B.

对于B来访问A的东西,你应该使用组合或继承。对于组合,给B指向A的对象,如下:

For B to access A's stuff, you should use composition or inheritance. For composition, give B a reference to an object of A, like so:

class B {
public:
  B(const A& aObj) : aRef(aObj) {
    cout << aRef.a << endl;
  }
private:
  const A& aRef;
};

对于继承,像这样:

class B: public A { // or private, depending on your desires
  B() {
    cout << a << endl;
  }
}

这篇关于C ++嵌套类,访问父类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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