2

首先我会给出一些代码,然后描述一个问题:

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字段是可以理解的。我知道这只是表明我在设计中犯了一个错误,但是有没有办法以一种优雅而简单的方式解决这个问题?

4

2 回答 2

2

如果您知道所有可点击内容都来自CGUIObject,则可以使用dynamic_cast

CClickable* obj = m_clickableObjectsList[i];

// Here I would like to also check if obj is visible
if(obj->wasClicked(clickPos) && dynamic_cast<CGUIObject*>(obj)->m_bVisible)
{
  //...

如果可点击不是 GUI 对象,则dynamic_cast在这种情况下将返回空指针,您应该在取消引用结果之前检查这一点。

于 2012-11-29T14:13:34.533 回答
1

而不是使用类似 a 的东西dynamic_cast,你必须实现wasClickedinCButton来说明按钮是否不可见,它没有被点击。

bool CButton::wasClicked() {
    if(!m_bVisible) return false;
    /*previous logic*/
}
于 2012-11-29T14:30:51.847 回答