【发布时间】:2016-05-15 13:09:46
【问题描述】:
我很难创建派生类并将方法指针从它传递给基类,以便在基类中声明的函数可以调用它(通过接口调用派生类的函数)。
我们的目标是创建派生类来带来它们自己的资源和函数,但是通过在基类提供的函数中调用其中一个函数来调用声明的函数应该是可能的。为此,我需要将派生的成员函数指针向下传递给基类。
这是我尝试过的:
class KeyFunction
{
void(*KeyFunction::KeyFuncPtr)() = nullptr; //pointer to a method of this class to store standard behavior for call
public:
KeyFunction(void(*KeyFunction::KeyFunc)()) : KeyFuncPtr(KeyFunc) {} //constructor which takes in standard behavior
void func() //standard call of the function
{
if(KeyFuncPtr)KeyFuncPtr(); //call with ensurance there's something to be called
}
void operator()() //make KeyFunction class callable
{
func();
}
};
class customRessource{
public:
string up = "UP";
string down = "DOWN";
};
class customKeyFunc : public KeyFunction
{
customRessource& r;
public:
void moveup() //possible behavior
{
cout << r.up;
}
void movedown()
{
cout << r.down;
}
customKeyFunc( void(*customKeyFunc::KeyFunc)() ) :KeyFunction( ( void(*KeyFunction::)() ) (KeyFunc) ){}
};
int main()
{
customKeyFunc Up(&(customKeyFunc::moveup)); //setup functions
customKeyFunc Down(&customKeyFunc::movedown);
Up(); //call functions
Down();
getchar();
return 0;
}
最后的 main 函数显示了使用该类的假定方式。
首先:我在每个类的构造函数中的类型变得疯狂(我尝试了很多关于如何正确编写成员指针的搜索,但我的语法仍然不稳定) 有人可以帮我把它们弄好吗?
我什至可以这样做(尤其是像我在 customKeyFunc 构造函数中那样向下转换成员指针)?我是以正确的方式接近这个还是我认为太复杂了?
提前感谢您的帮助!
【问题讨论】:
-
在我看来您正在尝试重新发明虚拟方法。重新发明轮子始终是一项艰巨的工作。
-
似乎是CRTP的用例
-
不使用虚函数有什么原因吗?
-
因为我不想...问题是我需要为每个函数创建一个新类(继承基),即使这些函数在相同的资源上工作,如果我这样做了虚函数
-
好的,但是您编写的任何内容都没有排除使用虚拟方法。
标签: c++ derived-class base-class member-function-pointers member-functions