构建一个 GUI 系统,我有几个类用于派生自基“GUIcontrol”类的不同 GUI 组件。我想要的是只有一个函数来返回任何类型的组件,但能够使用特定于该组件类型的函数(派生类的函数)。我注意到多态性方法将成为一个问题,我必须在基类中声明所有派生函数,这是不必要的,因为我永远不会只从基类创建对象。
class GUIcontrol {
protected:
std::string _name;
// these two methods (along with name()) will be used by all types
virtual void position(/*parameters*/)
virtual void useImage(/*parameters*/)
// these should be only in derived types
virtual void setHotSpot(/*parameters*/);
virtual void setScrollButtons(/*parameters*/);
public:
std::string name();
/*etc*/
}
class GUIbutton : public GUIcontrol {
public:
void setHotSpot(/*parameters*/);
}
class GUIscrollBar : public GUIcontrol {
public:
void setScrollButtons(/*parameters*/);
}
GUIcontrol* GUIsystem::getControl(std::string name);
问题是,如果我想添加更多 GUIbutton 或 GUIscrollBar 独有的功能,或任何其他派生 GUI 类的功能,我还必须在基类中将它们声明为虚拟的,这样编译器就不会提示像“setHotSpot”这样的东西不是它返回的基类的成员。
基类确实有成员函数会作用于所有的派生类,比如告诉对象应该放在什么位置,需要用什么图片,应该叫什么等等。但是我没有想要继续用其他函数填充基类,这些函数需要对某些派生类保持独占。
随着我不断添加更多虚函数,我最终会为基类得到一个巨大的 blob 对象。我可以用更简洁的方式设计它吗?请注意,我仍然不确定是否要对 getControl() 使用 static_cast/dynamic_cast 来解决这个问题,但只想知道是否有其他方法可以解决这个问题。
最佳答案
基类应仅包含所有控件通用功能的方法。
如果您打算使用仅对一种类型的控件有意义的功能,您应该检查该控件的类型是否正确,然后可以将其转换为该类型。
关于c++ - 比多态性更简洁的代码替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4708480/