C++:覆盖纯虚拟成员变量?

发布于 09-15 02:53 字数 662 浏览 4 评论 0原文

这个问题最好用代码来描述。我有一个名为 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 的类,它派生自 >ParamsEllVertex 派生自 Vertex。我想知道的是如何处理 EllVertexVertex 中的私有成员变量 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

王权女流氓2024-09-22 02:53:59

嗯...您需要以某种方式初始化 Vertex 中的 Params 。因此,将其作为 Vertex 构造函数的参数。然后,您的 EllVertex 将从其构造函数中将 EllParams 传递给父构造函数,这就是私有 Vertex.p 的初始化方式。

例如:

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;

    protected:
        Vertex(Params* inputParams) : p(inputParams) {}

    private:
        Params* const p;
};

请注意,我已将您的 p 成员变量更改为指针。这样,您就不必确保为 Params 或任何子类定义正确的复制构造函数。

Well...you need to initialize the Params in Vertex somehow. So make it a parameter on the Vertex constructor. Then your EllVertex will pass an EllParams to the parent constructor from its constructor and that will be how the private Vertex.p is initialized.

For example:

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;

    protected:
        Vertex(Params* inputParams) : p(inputParams) {}

    private:
        Params* const p;
};

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 for Params or any subclasses.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文