问题描述
我有一个类,可以调用它A,并且在该类定义内,我有以下:
I have a class, lets call it A, and within that class definition I have the following:
static QPainterPath *path;
这就是说,我声明一个静态;此类的所有实例现在将具有相同的共享数据成员。我想能够建立在这个类上,将其子类化为更专门的形式,分层行为,并且每个类都有自己唯一的路径对象(但不必重复无聊的位,如计算边界框或调用绘图例程)。
Which is to say, I'm declaring a static (class-wide) pointer to a path object; all instances of this class will now have the same shared data member. I would like to be able to build upon this class, subclassing it into more specialised forms, layering behaviour, and with each class having its own unique path object (but not having to repeat the boring bits like calculating bounding boxes or calling the painting routines).
如果我子类化它创建一个类F(例如),我想要F使用继承的绘图程序从A,但使用静态-wide)在F中声明的路径对象。我已经尝试在私有段中有上面的声明(并且在派生类F中重复它),并尝试在受保护段中使用它,都没有快乐。
If I subclass it to create a class F (for example), I want F to use the inherited drawing routines from A, but to use the static (class-wide) path object declared in F. I have tried having the declaration above in the private section (and repeating it in the derived class F), and tried having it in the protected section, all with no joy.
我可以看到为什么会发生这种情况:
I can sort of see why this is happening:
void A::paint() {
this->path...
指的是A :: path而不是F :: path,即使对象是F类。
is referring to A::path instead of F::path, even when the object is of class F.
有一个优雅的方式来绕过这个,并允许每个类维护一个静态路径对象,同时仍然使用在基类中定义的绘图代码,并且所有类(除了基类之外)是真实的和可实例化的。
Is there an elegant way to get round this, and allow each class to maintain a static path object, while still using drawing code defined in the base class, and having all classes (except perhaps the base class) be real and instantiatable?
推荐答案
使用虚方法获取对静态变量的引用。
Use a virtual method to get a reference to the static variable.
class Base {
private:
static A *a;
public:
A* GetA() {
return a;
}
};
class Derived: public Base {
private:
static B *b;
public:
A* GetA() {
return b;
}
};
请注意,B从这里派生。然后:
Notice that B derives from A here. Then:
void Derived::paint() {
this->GetA() ...
}
这篇关于子类化时覆盖静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!