【发布时间】:2011-07-03 09:51:41
【问题描述】:
我有一些难以解释的事情,所以我会尽力而为。我有一个 InstructionScreen 类,它显示箭头和文本块,解释每个按钮的作用等等。所以在 InstructionScreen 我有一堆成员函数,每个函数都会创建一些箭头和文本来解释不同按钮的作用。
InstructionScreen 将被子类化为 MenuInstructScreen、OptionsInstructScreen 等,在这些类中,我将创建自定义函数,这些函数将创建箭头和文本来解释它们的屏幕按钮。
问题在于在 InstructionScreen 中声明此堆栈,因为它将包含属于其子类的函数。我想我可以做到这一点,但我使用模板对吗?
简单来说,问题是如何声明一个堆栈,其中包含一个尚不存在的类的成员函数?
这个问题更容易理解&看看你看看这个简单的例子:
typedef class InstructionScreen;
typedef class MenuInstructScreen;
template <typename FooClass>
typedef void (FooClass::*MemberFuncPtr)(); // will be typedef void (MenuInstructScreen::*MemberFuncPtr)();
class InstructionScreen
{
public:
InstructionScreen() {}
void runInstructions()
{
while ( !instructionStep.empty() )
{
(this->*instructionStep.top())();
instructionStep.pop();
}
}
protected:
stack <MemberFuncPtr> instructionStep;
};
class MenuInstructScreen : public InstructionScreen
{
public:
MenuInstructScreen()
{
// Set instruction schedule
instructionStep.push( &MenuInstructScreen::step2() );
instructionStep.push( &MenuInstructScreen::step1() );
}
void step1()
{
// create some widgets that point to buttons & widgets that contain text instructions
}
void step2()
{
// create some widgets that point to buttons & widgets that contain text instructions
}
private:
};
class OptionsInstructScreen : public InstructionScreen
{
public:
OptionsInstructScreen()
{
// Set instruction schedule
instructionStep.push( &OptionsInstructScreen::step2() );
instructionStep.push( &OptionsInstructScreen::step1() );
}
void step1()
{
// create some widgets that point to buttons & widgets that contain text instructions
}
void step2()
{
// create some widgets that point to buttons & widgets that contain text instructions
}
private:
};
【问题讨论】:
-
指向成员函数的指针应该通过
&OptionsInstructScreen::step2获取。
标签: c++ function inheritance