C++ 我们可以有一个静态虚函数吗?如果不是,那为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9863007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:21:02  来源:igfitidea点击:

Can we have a static virtual functions? If not, then WHY?

c++static-methodsvirtual-functions

提问by Jatin

Possible Duplicate:
C++ static virtual members?

可能的重复:
C++ 静态虚拟成员?

Can we have a static virtual functions? If not, then WHY?

我们可以有一个静态虚函数吗?如果不是,那为什么?

class X
{
public:
       virtual static void fun(){} // Why we cant have static virtual function in C++?
};

回答by Oliver Charlesworth

No, because it doesn't make any sense in C++.

不,因为它在 C++ 中没有任何意义。

Virtual functions are invoked when you have a pointer/reference to an instanceof a class. Static functions aren't tied to a particular instance, they're tied to a class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function virtually.

当您拥有指向类实例的指针/引用时,将调用虚拟函数。静态函数不绑定到特定实例,它们绑定到一个类。C++ 没有指向类的指针,因此不存在您可以虚拟调用静态函数的情况。

回答by Kerrek SB

That would make no sense. The point of virtualmember functions is that they are dispatched based on the dynamic type of the object instanceon which they are called. On the other hand, static functions are not related to any instances and are rather a property of the class. Thus it makes no sense for them to be virtual. If you must, you can use a non-static dispatcher:

那没有任何意义。虚拟成员函数的要点在于它们是根据调用它们的对象实例的动态类型来调度的。另一方面,静态函数与任何实例无关,而是的属性。因此,它们是虚拟的毫无意义。如果必须,您可以使用非静态调度程序:

struct Base
{
    static void foo(Base & b) { /*...*/ }

    virtual ~Base() { }
    virtual void call_static() { foo(*this); /* or whatever */ }
};

struct Derived : Base
{
     static void bar(int a, bool b) { /* ... */ }

     virtual void call_static() { bar(12, false); }
};

Usage:

用法:

Base & b = get_instance();
b.call_static();   // dispatched dynamically

// Normal use of statics:
Base::foo(b);
Derived::bar(-8, true);