从基类调用派生类函数而不使用虚函数
嗨,假设我有这样的代码
// base class
class A {
public:
int CallMyFct(PtrToFCT what){
return what(10);
}
};
class B : public A {
int myInt;
public:
B():myInt(10){}
int myFct1(int val){
return myInt+val;
}
int myFct2(int val){
return myInt*2+val;
}
void Call(void){
int rez1=CallMyFct(&myFct1);
if (rez1!=20)
cout << "You are wrong" << endl;
int rez2=CallMyFct(&myFct2);
if (rez2!=30)
cout << "You are wrong" << endl;
}
};
现在我需要从基类调用这些 MyFct1、MyFct2 等,但我不能使用虚函数。所以这有点像继承反转。我不知道这是否可能。您认为 mem_fun 或任何其他适配器函数可以在这里工作吗?
我实际上需要弄清楚 PtrToFCT 是什么以及如何在 CallMyFCT 中传递 myFct1。
谢谢
Hi suppose I have a code like this
// base class
class A {
public:
int CallMyFct(PtrToFCT what){
return what(10);
}
};
class B : public A {
int myInt;
public:
B():myInt(10){}
int myFct1(int val){
return myInt+val;
}
int myFct2(int val){
return myInt*2+val;
}
void Call(void){
int rez1=CallMyFct(&myFct1);
if (rez1!=20)
cout << "You are wrong" << endl;
int rez2=CallMyFct(&myFct2);
if (rez2!=30)
cout << "You are wrong" << endl;
}
};
Now I need to call these MyFct1, MyFct2, etc. from the base class, but I can not use virtual functions. So it is sorta like inversion of inheritance. I dont know if thats even possible. Do you think mem_fun or any other adapter function would work here.
I actually need to figure out what would be that PtrToFCT and how the would I pass myFct1 in the CallMyFCT.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须将要调用的函数定义为
static
,并提供附加参数以将它们传递给对象实例(而不是如果调用为this
,它们将获得常规成员函数)。You have to define the functions to be called as
static
, and provide additional parameter to pass to them to the object instance (instead ofthis
that they would be getting if called as regular member functions).您可以使用
[boost::function<>]
1,在 C++2011 中也称为std::function
,源自
。您没有说明为什么不能使用虚拟功能。目前尚不清楚该方法是否比虚拟函数提供了性能增强,但还有其他原因不使用虚拟函数。无论如何,这满足(我的解释)您从基类调用函数的要求,这些函数的行为根据实际的派生类而有所不同,而不使用虚函数。我并不完全清楚你所期望的用途的例子。如果这个机制不能满足您的需求,请明确需求。
You can do what you like more cleanly with
[boost::function<>]
1, also known asstd::function
from<functional>
in C++2011. You do not state why you cannot use virtual functions. It is not clear that this method offers a performance enhancement over virtual functions, but there are other reasons not to use virtual functions.In any event, this meets (my interpretation of) your requirements for calling functions from the base class that behave differently depending on the actual derived class without use of virtual functions. Your example of desired use is not completely clear to me. If this mechanism does not meet your needs, please clarify the needs.