从基类实现一个以静态方式派生的虚拟方法 [英] implement a virtual method from the base class as derived in static

查看:84
本文介绍了从基类实现一个以静态方式派生的虚拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有虚拟方法的抽象基类.在派生类中,实现了此方法.但是,我希望派生类中的函数为静态方法,以便能够在不实例化该类的对象的情况下调用该函数.

I have an abstract base class with a virtual method. In the derived class, this method is implemented. However, I want the function in the derived class as a static method in order to be able to call the function without instantiating an object of that class.

class Base 
{
   virtual double Foo(double rParam) const;
};

class Derived1 : public Base
{
   static double Foo(double rParam);
};

class Derived2 : public Base
{
   static double Foo(double rParam);
};

本质上,Derived1和Derived2提供了静态函数的不同实现(不依赖于对象数据),但是我希望这些函数是虚拟的,以便能够在基类的其他函数中调用这些函数.我现在看到的唯一解决方案是在派生类中实现两个成员函数,一个是基类的虚函数,另一个(具有不同的名称)是静态函数.为了防止源代码加倍,虚拟函数可以直接调用静态函数(可以内联).还有其他解决方案吗?

Essentially, Derived1 and Derived2 provide different implementations of a static function (that do not depend on object data), but I want those functions to be virtual in order to be able to call those functions in other functions of the base class. The only solution I see right now is to implement two member functions in the derived class, one being the virtual function from the base class, and the other one (with a different name) being a static function. In order to prevent doubling the source code, the virtual function could then directly call the static function (could be inlined). Any other solutions?

class Derived : public Base
{
   double Foo(double rParam)const
   {
       return FooStatic(rParam);
   }

   inline static double FooStatic(double rParam);
};

推荐答案

将虚拟方法设为静态是没有意义的.虚拟意味着您可以根据对象的类型选择要运行的实现.在静态上下文中,您没有对象.

It would not make sense to make a virtual method static. Virtual means that you choose which implementation to run based on the type of an object. In a static context you have no object.

虽然第一个示例将编译,但不会执行您期望的操作.静态方法不会覆盖基本实现,而是将其隐藏,这意味着将永远不会调用静态方法,而不会调用基类.第二个示例很好,但是我看不到任何问题.

While the first example will compile, it will not do what you expect it to do. The static methods will not override the base implementation, but rather hide it, meaning that the static methods will never be called instead of that of the base class. The second example is fine though, I cannot see any problem with it.

这篇关于从基类实现一个以静态方式派生的虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆