c ++如何使用合成扩展一个类?

时间:2014-03-18 04:36:21

标签: c++ inheritance encapsulation composition

我最近遇到了以下问题。我有一个Base类,它有一个Base_encapsulated_class。

class Base_class
{
public:
    Base_class(int int_value, short short_value) :
      m_encapsulated_class(int_value, short_value)
    {};

    ~Base_class(void){};

    Base_encapsulated_class  m_encapsulated_class;
};

class Base_encapsulated_class
{
public:
    Base_encapsulated_class(int int_value, short short_value)
        : m_int(int_value),
        m_short(short_value)
    {};

    ~Base_encapsulated_class(void){};

private:
    int m_int;
    short m_short;
};

现在我想扩展Base_classBase_encapsulated_class来实现:

class Derived_class : public Base_class
{
public:
    Derived_class(int int_value, short short_value, bool boolean_value) :
      Base_class(int_value, short_value)
    {};

    ~Derived_class(void)
    {};

    Derived_encapsulated_class m_encapsulated_class;

};

class Derived_encapsulated_class : public Base_encapsulated_class
{
public:
    Derived_encapsulated_class(int int_value, short short_value, bool boolean_value) :
      Base_encapsulated_class(int_value, short_value),
          m_bool(boolean_value)
    {
    }

    ~Derived_encapsulated_class(void)
    {
    }

private:
    bool m_bool;
};

这种方法在派生类对象中给出了两个m_encapsulated_class实例,这显然在c ++中是合法的(我有点惊讶)。

但这不是我想要的。我想在我的派生类中有一个m_encapsulated_class成员。那么可以在基类中扩展复合成员吗?

1 个答案:

答案 0 :(得分:1)

您可以使用虚拟getter强制继承成员:

class Base_class
{
public:
    Base_class(int int_value, short short_value) :
      m_encapsulated_class(int_value, short_value)
    {};

protected:
    virtual Base_encapsulated_class Get_encapsulated_class() /* = 0 if you want to enforce encapsulated derivation */
    {
       return m_encapsulated_class;
    }


private:
    Base_encapsulated_class  m_encapsulated_class;
};


class Derived_class : public Base_class
{
public:
    Derived_class(int int_value, short short_value, bool boolean_value) :
      Base_class(int_value, short_value)
    {};

    ~Derived_class(void)
    {};

protected:
    virtual Base_encapsulated_class Get_encapsulated_class() 
    {
       return m_derived_encapsulated_class;
    }

private:

    Derived_encapsulated_class m_derived_encapsulated_class;

};