我们可以拥有静态虚拟功能吗?如果没有,那么为什么?
class X
{
public:
virtual static void fun(){} // Why we cant have static virtual function in C++?
};
答案 0 :(得分:65)
不,因为它在C ++中没有任何意义。
当指针/引用指向类的实例时,将调用虚函数。静态函数不依赖于特定实例,它们与类绑定。 C ++没有指向类的指针,因此没有可以虚拟调用静态函数的方案。
答案 1 :(得分:14)
这没有任何意义。 虚拟成员函数的要点是,它们是根据调用它们的对象实例的动态类型调度的。另一方面,静态函数与任何实例无关,而是类的属性。因此,他们虚拟是没有意义的。如果必须,您可以使用非静态调度程序:
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);