C++ 避免在C+中的继承层次结构中重复代码+;
我在继承层次结构中的重复代码方面遇到了一些困难。 如何避免重复函数smile()中的代码 鉴于基类中不存在变量C++ 避免在C+中的继承层次结构中重复代码+;,c++,inheritance,code-duplication,C++,Inheritance,Code Duplication,我在继承层次结构中的重复代码方面遇到了一些困难。 如何避免重复函数smile()中的代码 鉴于基类中不存在变量\u a,我无法将函数移到那里。同样,创建这样的模板函数template void smile(T&a){a++;}对我来说也不是一个真正的解决方案。我的实际代码有点复杂,如果不是不可能应用到我当前的设计中,这样的解决方案将非常混乱 class com { public: com(int x, float y) : _x(2), _y(1.15f) { } protect
\u a
,我无法将函数移到那里。同样,创建这样的模板函数template void smile(T&a){a++;}
对我来说也不是一个真正的解决方案。我的实际代码有点复杂,如果不是不可能应用到我当前的设计中,这样的解决方案将非常混乱
class com
{
public:
com(int x, float y) : _x(2), _y(1.15f)
{ }
protected:
// Common functions go here .We need this base class.
protected:
int _x;
float _y;
};
class com_int : public com
{
public:
void fill()
{ _a = std::max(_x, (int)_y); }
protected:
int _a;
};
class com_real : public com
{
public:
void fill()
{ _a = std::min((float)_x, _y); }
protected:
float _a;
};
class happy_int : public com_int
{
public:
void smile() { _a ++; } // BAD: Will be duplicated
};
class happy_float : public com_real
{
public:
void smile() { _a ++; } // BAD: Duplicated code
}
class sad_int : public com_int
{
public:
frown() { _a --; }
}
也有人知道一本好的书,教你如何用OOP和模板原理在C++中设计代码吗?p> 您可以从其他帮助器模板继承:
template <typename T, typename Derived> struct filler
{
T _a;
void fill()
{
com & b = static_cast<Derived&>(*this);
_a = std::min(b._x, b._y);
}
};
模板结构填充
{
T_a,;
填空()
{
com&b=静态演员表(*本);
_a=标准::最小值(b.x,b.y);
}
};
用法:
struct com_int : com, filler<int, com_int> { };
structcom_int:com,filler{};
您的示例似乎没有真正说明您的问题,因为使用模板将是您的示例的正确答案。了解真实情况的哪些方面导致模板不是有效选项会很有趣。正如@VaughnCato所说,模板将足以避免重复执行smile()。但是如果你不能,为什么不考虑多重继承呢?如果有适当的限制,它可能是好的。