【问题标题】:How to optimally implement functionality common between subset of inherited classes如何以最佳方式实现继承类子集之间的通用功能
【发布时间】:2013-07-29 16:39:31
【问题描述】:

我正在寻找一种最佳方式来实现接口实现子集之间的通用代码。为了具体描述它假设我们有一个由 A、B 和 C 实现的接口 P。再次假设 A 和 B 具有某些共同的功能(公共代码),B 和 C 具有某些共同的功能,同样 A 和 C 具有共同的功能在接口的实现中。我明白了:

  1. 我们可以为每一对创建中间类,包含公共功能,然后从中间类派生类,例如,中间类 AB 实现 A 和 B 之间的公共代码,BC 实现 B 和 C 之间的公共代码,然后派生B 来自 AB 和 BC。
  2. 为每对中的类复制代码

1 理论上应该是最佳解决方案,但是,实际上它会造成巨大的混乱,因为实际上我不仅有 3 个实现接口的类,而且还有大量的类。此外,共同的功能不仅在对之间,而且在类的大子集之间,并且有很多这样的子集。因此,我们需要有大量的中间类来实现不同子集之间的通用功能。这使得通过中间类实现变得困难/低效,因为我们需要大量的这些中间类。

我相信2也不是最好的解决方案,因为它需要代码复制,这会导致代码维护的问题。

编辑:我已尝试简化问题以提供清晰的图片以回应 cmets。

【问题讨论】:

  • 继承应该用于接口/替换。 P 是否描述了子类实现的接口?
  • 4- 使用接口,你可以有一个以这个接口为参数的函数来做公共代码
  • 除非您要查看任意 B 和 C 来执行 X,任意 A 和 B 来执行 Y,以及 A、B 和 C 来执行 Z,否则您可能宁愿组合而不是继承.
  • 功能是否涉及P所缺乏的界面功能?
  • 给我们一个用例,因为我没有真正看到您概述的解决方案的问题。如果 A 和 B 有共同的功能,但 A 和 B 以外的任何人都无法使用,那么您应该以某种方式表达这种依赖关系。如果我将 A 和 B 之间的通用功能一起收集到 AB 中,AB 被继承(私有?)或聚合(私有成员?)到 A 和 B 中的方式是什么?

标签: c++ object inheritance polymorphism


【解决方案1】:

您可以在模板函数中定义您的通用实现,并根据需要从每个类中调用它们以实现接口函数。

使用您的接口 P,类 A、B 和 C,它给出以下内容。

struct P {
    virtual int X() = 0;
};

template <typename T>
int CommonAB( T const & t ) { return t.x; }

template <typename T>
int CommonBC( T const & t ) { return t.y; }

template <typename T>
int CommonCA( T const & t ) { return t.x+t.y; }


struct A : public P {
    int X() { return CommonAB( *this )+CommonCA( *this ); }
protected:
    int x;
    int y;
friend int CommonAB<A>( A const & );
friend int CommonCA<A>( A const & );
};

struct B : public P {
    int X() { return CommonBC( *this )+CommonAB( *this ); }
protected:
    short x;
    short y;
friend int CommonBC<B>( B const & );
friend int CommonAB<B>( B const & );
};

struct C : public P {
    int X() { return CommonCA( *this )+CommonBC( *this ); }
protected:
    char x;
    char y;
friend int CommonCA<C>( C const & );
friend int CommonBC<C>( C const & );
};


int main()
{
    A a;
    B b;
    C c;

    a.X();
    b.X();
    c.X();

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2019-01-11
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多