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

时间:2021-12-09 20:23:45

Consider the following class definitions:

考虑以下类定义:

#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;
};

In an appropriate implementation, I would like to create the following types of CObject storage objects:

在适当的实现中,我想创建以下类型的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();

However, the current CObject definition does not prevent mixing CParty and CTransaction types which are incompatible with one another:

但是,当前的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();

Is it somehow possible to place a restriction on how the two objects can be linked together inside a CObject instance?

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

1 个解决方案

#1


You could encapsulate the decision in the CObject constructor:

您可以将决策封装在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();
    }
}

#1


You could encapsulate the decision in the CObject constructor:

您可以将决策封装在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();
    }
}