首先我会给出一些代码,然后描述一个问题:
class CGUIObject
{
protected:
int m_id;
bool m_bVisible;
// Other non-relevant fields and methods specific for gui object...
};
class CClickable
{
private:
bool m_bClicked;
public:
bool isClicked();
void setClicked(bool bClicked);
virtual bool wasClicked(const TPoint& clickPos) = 0;
// Other non-relevant fields and methods specific for clickable object...
};
class CComponent : public CGUIObject
{
// The only important part of this class is that it derives from CGUIObject
};
class CButton : public CComponent, CClickable
{
// The only important part of this class is that it derives from CComponent and CClickable
};
// Now there is a method in my EventManager which informs all clickables about left mouse click event
void CEventManager::lMouseButtonClickEvent(const CPoint& clickPos)
{
// Go through all clickables
for(unsigned int i = 0; i < m_clickableObjectsList.size(); i++)
{
TClickable* obj = m_clickableObjectsList[i];
// Here I would like to also check if obj is visible
if(obj->wasClicked(clickPos))
{
obj->setClicked(true);
if(obj->m_pOnClickListener != nullptr)
obj->m_pOnClickListener->onClick();
return; // Only one object can be clicked at once
}
}
}
好的,如您所见:
- CButton 派生自 CComponent 和 CClickable
- CComponent 派生自 CGUIObject
- CGUIObject 有
m_bVisible
对我很重要的字段 - 在 EventManager 我创建了一个 CClickable* 对象列表
现在我想通知被点击的特定 CClickable 对象,但前提是它是可见的。我知道所有可点击对象也派生自 CGUIObject(例如 CButton),但它是 CClickable* 的列表,因此我无法访问m_bVisible
字段是可以理解的。我知道这只是表明我在设计中犯了一个错误,但是有没有办法以一种优雅而简单的方式解决这个问题?