【问题标题】:Avoid duplicated code in inheritance hierarchy in C++避免 C++ 继承层次结构中的重复代码
【发布时间】:2012-07-15 23:33:17
【问题描述】:

在我的一个继承层次结构中重复代码时遇到了一些困难。 如何避免在函数 smile() 中重复代码?

鉴于变量_a 不存在于基类中,我无法将函数移到那里。同样创建一个像 template<typename T> 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++ 中实际设计代码的好书吗?

【问题讨论】:

  • 您的示例似乎并不能真正说明您的问题,因为使用模板将是您示例的正确答案。
  • 看看实际情况的哪些方面导致模板不是有效选项会很有趣。
  • 正如@VaughnCato 所说,模板将足以避免重复实现微笑()。但是如果你不能,你为什么不考虑多重继承呢?适当的限制可能会很好。

标签: c++ inheritance code-duplication


【解决方案1】:

你可以从另一个帮助模板继承:

template <typename T, typename Derived> struct filler
{
    T _a;
    void fill()
    {
        com & b = static_cast<Derived&>(*this);
        _a = std::min(b._x, b._y);
    }
};

用法:

struct com_int : com, filler<int, com_int> { };

【讨论】:

    猜你喜欢
    • 2011-01-22
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    相关资源
    最近更新 更多