c++ 中的静态虚函数
我有一个基类和一个派生类,我想更改基函数,同时保持它们静态,因为它们应该作为静态传递给其他函数。
我怎样才能做到这一点?
I have a base class and a derived one and I want to change base functions while keeping them static as they should be passed to other functions as static.
How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
ATL 框架通过将基类设为模板,然后让派生类将其类类型作为模板参数传递,从而绕过了无虚拟静态的限制。然后,基类可以在需要时调用派生类静态,例如:
这被称为奇怪的重复模板模式,它可以是用于实现静态多态性。
The ATL framework gets around the limitation of no virtual statics by making the base class be a template, and then having derived classes pass their class type as a template parameter. The base class can then call derived class statics when needed, eg:
This is known as Curiously recurring template pattern, which can be used to implement static polymorphism.
您的意思是您需要一个指向静态函数的指针(例如,作为参数传递给另一个需要指向静态函数的指针的函数),但您需要虚拟地访问该函数指针?在这种情况下,使用虚函数来获取函数指针:
Do you mean you need a pointer to a static function (e.g. to pass as an argument to another function that requires a pointer to a static function), but you need to access that function pointer virtually? In that case, use a virtual function to get the function pointer:
静态函数不能是虚拟的,因为它们没有可以访问它们的实例。我相信你可以覆盖它们。
static function can not be virtual since they do not have an instance through which they are accessed. I do believe you can overwrite them though.
C++ 中不能有静态虚函数。
You can't have static virtual functions in C++.
虚拟函数通常依赖
this
指针来确定运行时调用的函数类型。静态成员函数不会传递
this
,因此 C++ 中不允许静态虚函数。Virtual functions typically rely on
this
pointer to determine the type of function to be called at run time.A static member function does not pass a
this
so static virtual functions are not allowed in C++.如果我正确理解你的问题,那么你可以遵循以下方法,否则忽略..
在基类中有静态函数指针。
在基类中有一个静态函数(其中您使用该静态函数指针调用该函数)..
在派生类中将该静态函数指针设置为您希望执行的函数定义..(在基类中您可以设置该函数指向某个默认函数的指针)。
If i am correct in understanding ur question, then u can follow the following approach otherwise ignore..
have static function pointer in the base class.
in base class have a static function ( in which u call the function by using that static function pointer)..
in derived classes set that static function poiter to the function defination u wish to execute.. ( in base class u can set the function pointer to some default function).
您不能拥有静态虚拟函数,因为拥有它们没有意义。
You cannot have static virtual functions, because it doesn't make sense to have them.