我有这样的类结构:
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
添加到命令行。
其次,嵌套类不能立即访问外部类的实例。它们仍然需要用指针或对“父”的引用来构造。鉴于B
和C
的继承关系,以下可能适合您;
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_
}
};
关于c++ - 使用父类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36835652/