我有一個基類自選畫面&我希望始終在其構造函數中調用函數initComponents(),即使對於此類的子類也是如此。但是如果子類已經覆蓋了initComponents()函數,那麼我想讓MyClass調用子類的initComponents()版本,而不是initComponents()的超類(MyScreen)版本。父類可能會調用其子類版本的函數
是否有可能在MyClasses構造函數中做到這一點?
class MyScreen
{
public:
MyScreen()
{
// a child of this class (& any instance of this class) should always call the initComponents() from this constructor
initComponents();
}
void initComponents()
{
// initialise mainLayout, etc, usually this function wont be overridden, sometimes it will be
}
protected:
Layout *mainLayout;
};
class MenuScreen : public MyScreen
{
public:
MenuScreen : public MyScreen()
{
// I know I could just call initComponents from here, but this is just an example, somethings must be called from the base class
}
void initComponents()
{
// create layout, set main layout etc.
mainLayout = new MenuLayout(...);
}
};
不可以。把你的構建邏輯放在構造函數中。 – 2011-04-22 11:00:12