使用父类中的变量

时间:2016-04-25 08:40:21

标签: c++ class

我有这种类的结构:

class A {
  class B;
  class C;
  int updates = 0;  // invalid use of non-static data member 'A::updates'
  C* example;
  class B {
   public:
    // ...
    void up_plus() {
      updates++;  // problem here is too
    }
    // And some other methods.......
  };
  class C : public B {
   public:
    int size;
    // ...
    void sizeup() {
      example->size++;  // invalid use of non-static data member 'A::header'
    }
    // And some other methods....
  };
};

我的问题是,如何修复此结构?在Java中,这将有效,但这里存在问题。

1 个答案:

答案 0 :(得分:1)

The syntax;

class A {
    int updates = 0; // allowed in C++11 and above
// ...

Is allowed with compiling for the C++11 standard and above. Assuming you are using clang or g++, add -std=c++11 or -std=c++14 to the command line.

Secondly, nested classes do not have immediate access to an instance of the outer class. They still need to be constructed with a pointer or reference to the "parent". Given the inheritance relationship of B and C, the following could be suitable for you;

  class B {
   protected:
    A* parent_;
   public:
    B(A* parent) : parent_(parent) {}
    void up_plus() {
      parent_->updates++; // addition of parent_
    }
  };
  class C : public B {
   public:
    int size;
    void sizeup() {
      parent_->example->size++; // addition of parent_
    }
  };

Working sample here.

相关问题