C++ 如何最佳地实现继承类子集之间的公共功能
我正在寻找一种实现接口实现子集之间通用代码的最佳方法。为了具体描述它,假设我们有一个由A、B和C实现的接口P。同样,假设A和B具有某些公共功能(公共代码),B和C具有某些公共功能,类似地,A和C在接口的实现中具有公共功能。我明白:C++ 如何最佳地实现继承类子集之间的公共功能,c++,object,inheritance,polymorphism,C++,Object,Inheritance,Polymorphism,我正在寻找一种实现接口实现子集之间通用代码的最佳方法。为了具体描述它,假设我们有一个由A、B和C实现的接口P。同样,假设A和B具有某些公共功能(公共代码),B和C具有某些公共功能,类似地,A和C在接口的实现中具有公共功能。我明白: 我们可以为每一对创建包含公共功能的中间类,然后从中间类派生类,例如,中间类AB实现A和B之间的公共代码,中间类BC实现B和C之间的公共代码,然后从AB和BC派生B 为每对中的类复制代码 理论上,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;
}
struct P{
虚拟整数X()=0;
};
模板
int CommonAB(T const&T){返回T.x;}
模板
int CommonBC(T const&T){返回T.y;}
模板
int CommonCA(T const&T){返回T.x+T.y;}
结构A:公共P{
int X(){return CommonAB(*this)+CommonCA(*this);}
受保护的:
int x;
int-y;
共同的朋友(一个常数&);
共同的朋友(一个常数&);
};
结构B:公共P{
int X(){return CommonBC(*this)+CommonAB(*this);}
受保护的:
短x;
短y;
普通的朋友(B常数&);
普通的朋友(B常数&);
};
结构C:公共P{
int X(){return CommonCA(*this)+CommonBC(*this);}
受保护的:
字符x;
chary;
普通的朋友(C常量&);
friend int CommonBC(C const&);
};
int main()
{
A A;
B B;
C C;
a、 X();
b、 X();
c、 X();
返回0;
}
继承应用于接口/替换。P
描述了由子类实现的接口吗?4-使用接口,您可以使用一个函数,将此接口作为参数来执行公共代码,除非您要查看任意B和Cs执行X,任意a和Bs执行Y,以及a、B和C执行Z,您可能更喜欢组合而不是继承。功能是否涉及P所缺少的接口功能?请给我们一个用例,因为我并不认为您概述的解决方案存在问题。如果A和B有共同的功能,除了A和B之外,其他任何人都无法使用,那么您应该以某种方式表达这种依赖关系。如果我将A和B之间的公共功能一起收集到AB中,AB以何种方式被继承(私人?)或聚合(私人成员?)到A和B中是不恰当的?