C++中的静态函数是否可以是虚拟的?

在C++中,类的静态成员函数不能是虚拟的。当有指向类实例的指针或引用时,会调用虚拟函数。静态函数与类的实例无关,但与类有关。C++没有指向类的指针,所以没有任何一种方法可以在实际中调用静态函数。

null

例如,下面的程序给出编译错误,

CPP

// CPP Program to demonstrate Virtual member functions
// cannot be static
#include <iostream>
using namespace std;
class Test {
public :
virtual static void fun() {}
};


输出

prog.cpp:9:29: error: member ‘fun’ cannot be declared both virtual and static
    virtual static void fun() {}
                            ^

此外,静态成员函数不能为空 康斯特 不稳定的 .以下代码也无法编译,

CPP

// CPP Program to demonstrate Static member function cannot
// be const
#include <iostream>
using namespace std;
class Test {
public :
static void fun() const {}
};


输出

prog.cpp:8:23: error: static member function ‘static void Test::fun()’ cannot have cv-qualifier
    static void fun() const {}
                      ^

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享