C++:覆盖纯虚拟成员变量?
这个问题最好用代码来描述。我有一个名为 Vertex
的类,其中包含名为 Params
的类的实例:
class Params {
virtual Params operator + (Params const& p) = 0;
};
class Vertex {
public:
Params operator + (Params const& ap) const {
return p + ap
};
virtual float eval() = 0;
private:
Params const p;
};
我还有一个名为 EllParams
的类,它派生自 >Params
和 EllVertex
派生自 Vertex
。我想知道的是如何处理 EllVertex
中 Vertex
中的私有成员变量 p
:我希望它的类型为 EllParams
。有没有办法使 p
虚拟/覆盖它?或者我应该寻找模板来寻找解决方案?
This question is best described in code. I have a class called Vertex
that contains an instance of a class called Params
:
class Params {
virtual Params operator + (Params const& p) = 0;
};
class Vertex {
public:
Params operator + (Params const& ap) const {
return p + ap
};
virtual float eval() = 0;
private:
Params const p;
};
I also have a class called EllParams
which is derived from Params
and EllVertex
which is derived from Vertex
. What I'm wondering is how to deal with the private member variable p
in Vertex
in EllVertex
: I want it to be of type EllParams
. Is there some way of making p
virtual/overriding it? Or should I look to templates for a solution?
嗯...您需要以某种方式初始化
Vertex
中的Params
。因此,将其作为 Vertex 构造函数的参数。然后,您的EllVertex
将从其构造函数中将EllParams
传递给父构造函数,这就是私有Vertex.p
的初始化方式。例如:
请注意,我已将您的
p
成员变量更改为指针。这样,您就不必确保为Params
或任何子类定义正确的复制构造函数。Well...you need to initialize the
Params
inVertex
somehow. So make it a parameter on theVertex
constructor. Then yourEllVertex
will pass anEllParams
to the parent constructor from its constructor and that will be how the privateVertex.p
is initialized.For example:
Notice that I have changed your
p
member variable to a pointer. That way, you don't have to ensure that a correct copy constructor is defined forParams
or any subclasses.