c++ - 通过组合添加类功能

标签 c++ inheritance polymorphism const-reference

假设我们有一个抽象类ElementTriangleQuadrilateral 都派生自该抽象类。

假设这些类与依赖于元素形状的插值方法结合使用。因此,基本上我们创建了一个抽象类 InterpolationElement,我们从中派生了 InterpolationTriangleInterpolationQuadrilateral

然后,为了在 TriangleQuadrilateral 类中包含插值功能,我们在类的 Element 中添加一个常量引用数据成员键入 InterpolationElement,即:

class Element
{
public:
    Element(const InterpolationElement& interp);

    const InterpolationElement& getInterpolation() const;

private:
    const InterpolationElement& interpolation;
};

然后我们创建一个方法(如 Scott Meyers,Effective C++ 所述),将 InterpolationTriangle 类的局部静态对象实例化为

const InterpolationTriangle& getInterpolationTriangle()
{
    static InterpolationTriangle interpolationTriangle;

    return interpolationTriangle;
}

所以 Triangle 类可以像这样构造:

class Triangle : public Element
{
public:
    Triangle() : Element( getInterpolationTriangle() ) {}
};

这是我的问题:为了在我的类 Element 上合并插值方法,这种方法是否正确?这个用在专业场景吗?

我可以直接在类 Element 上实现所有插值方法(作为纯虚拟),并在派生类 TriangleQuadrilateral 中覆盖它们>。然而,这种方法在我看来很麻烦,因为每次我需要改进或实现新的插值功能时,我都必须在这些类上这样做。此外,使用这种方法,类变得越来越大(许多方法)。

我想听听你的一些建议和意见

提前致谢。


其他详细信息:

class InterpolationElement
{
public:
    InterpolationElement();

    virtual double interpolationMethod1(...) = 0;
                      :
    virtual double interpolationMethodN(...) = 0;
}

class InterpolationTriangle : public InterpolationElement
{
public:
    InterpolationTriangle () {}

    virtual double interpolationMethod1(...) { // interpolation for triangle }
                      :
    virtual double interpolationMethodN(...) { // interpolation for triangle }
}

class InterpolationQuadrilateral : public InterpolationElement
{
public:
    InterpolationTriangle () {}

    virtual double interpolationMethod1(...) { // interpolation for quadrilateral}
                      :
    virtual double interpolationMethod1(...) { // interpolation for quadrilateral}
}

最佳答案

这些类与插值方法结合使用。为什么这些方法需要在单例对象中?这里的单例看起来很有问题。

class Element
{
public:
    virtual double interpolationMethod1(...) = 0;
                  :
    virtual double interpolationMethodN(...) = 0;

};

class Triangle : public Element
{
public:
    virtual double interpolationMethod1(...) { // interpolation for triangle }
                  :
    virtual double interpolationMethodN(...) { // interpolation for triangle }
}

此外,欢迎来到 SO!

关于c++ - 通过组合添加类功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3471968/

相关文章:

C# - 访问说明符 - 用于访问同一命名空间中的方法

c++ - 智能指针的 const 正确性

c++ - 纯虚拟类上的 DECLSPEC_NOVTABLE?

c++ - 异步显示 Qt 对话框

c++ - 为什么两个 vector 的大小<bool> bVec = { true,false,true,false,true}; vector <字符> cVec = { 'a' , 'b' , 'c' , 'd' , 'e' };是不同的?

C++ Builder 如何将控制台应用程序转换为 VCL 控制台应用程序?

C++ 继承和具有虚拟辅助函数的 Pthreads

c++ - 如何将 Parent* 对象(指向 &Child 对象)插入 vector<Child> 中?

C++ 使用纯虚函数实例化抽象类的子类

c++ - 重载虚拟方法与非虚拟方法有何不同?