如何在容器内强制实现两个独立类的父/派生关系?

时间:2015-05-08 07:50:51

标签: c++ pointers polymorphism containers vtable

考虑以下类定义:

#include <string>

class CParty
{
public:
    CParty();
    virtual ~CParty();
    int m_nId;
};

class CPartyEx : public CParty
{
public:
    CPartyEx();
    ~CPartyEx();
    std::string m_sName;
};

class CTransaction
{
public:
    CTransaction();
    virtual ~CTransaction();
    int m_nClassNo;
};

class CTransactionEx : public CTransaction
{
public:
    CTransactionEx();
    ~CTransactionEx();
    std::string m_sDesc;
};

class CObject
{
public:
    CObject();
    ~CObject();
    CParty* m_pParent;
    CTransaction* m_pTransaction;
};

在适当的实现中,我想创建以下类型的CObject存储对象:

// OK: Basic party with basic transaction
CObject iObject1;
iObject1.m_pParent = new CParty();
iObject1.m_pTransaction = new CTransaction();

// OK: Extended party with extended transaction
CObject iObject2;
iObject2.m_pParent = new CPartyEx();
iObject2.m_pTransaction = new CTransactionEx();

但是,当前的CObject定义并不能防止混合彼此不兼容的CParty和CTransaction类型:

// Not intended: Basic party with extended transaction
CObject iObject3;
iObject3.m_pParent = new CParty();
iObject3.m_pTransaction = new CTransactionEx();

// Not intended: Extended party with basic transaction
CObject iObject4;
iObject4.m_pParent = new CPartyEx();
iObject4.m_pTransaction = new CTransaction();

是否有可能限制两个对象如何在CObject实例中链接在一起?

1 个答案:

答案 0 :(得分:1)

您可以将决定封装在CObject构造函数中:

class CObject
{
public:
    CObject(bool extended = false);
};

CObject::CObject (bool extended)
{
    if (extended)
    {
        m_pParent = new CPartyEx();
        m_pTransaction = new CTransactionEx();
    }
    else
    {
        m_pParent = new CParty();
        m_pTransaction = new CTransaction();
    }
}