c++ - 使用父类中的变量

标签 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 中这是可行的,但这里有一个问题。

最佳答案

语法;

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

允许针对 C++11 标准及更高版本进行编译。假设您使用的是 clang 或 g++,请将 -std=c++11-std=c++14 添加到命令行。

其次,嵌套类不能立即访问外部类的实例。它们仍然需要用指针或对“父”的引用来构造。鉴于BC的继承关系,以下可能适合您;

  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 .

关于c++ - 使用父类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36835652/

相关文章:

c++ - 自动生成函数头,可变参数模板

python - 将闭包从 Cython 传递到 C++

c++ - 在 C++ 中,对象 vector 是在堆上分配还是在堆栈上分配?

c++ - C++如何使用CMakeList.txt链接mongoc和mongocxx静态库

javascript - React 组件中的不同区域

Java OOP transient 字段在加载 POJO 父级时初始化

c++ - 为什么我们需要 [basic.scope.class]/2?

c++递归大数以查找mod

ruby - 数字1上的实例方法从何而来

java - 为什么不是所有的 Java 类都有接口(interface)?