我们可以有一个静态的虚拟功能吗? 如果不是,那么为什么?

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

我们可以有一个静态的虚拟功能吗? 如果不是,那么为什么?

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

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

当你有一个指针/对一个类的实例的引用时,虚拟函数被调用。 静态函数不与特定的实例绑定,它们绑定到一个类。 C ++没有指向类的指针,所以没有可以虚拟调用静态函数的场景。


这是没有道理的。 虚拟成员函数的要点是,它们根据调用它们的对象实例的动态类型进行调度。 另一方面,静态函数与任何实例都没有关系,而是该类的一个属性。 因此,对他们来说虚拟是没有意义的。 如果您必须,您可以使用非静态调度程序:

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); }
};

用法:

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

// Normal use of statics:
Base::foo(b);
Derived::bar(-8, true);
链接地址: http://www.djcxy.com/p/9177.html

上一篇: Can we have a static virtual functions? If not, then WHY?

下一篇: What does classmethod do in this code?