Can we have a virtual static method ? (c++) [dupli

2019-04-03 01:40发布

Possible Duplicate:
C++ static virtual members?

Can we have a virtual static method (in C++) ? I've tried to compile the following code :

#include <iostream>
using namespace std;

class A
{
public:
    virtual static void f() {cout << "A's static method" << endl;}
};

class B :public A
{
public:
    static void f() {cout << "B's static method" << endl;}
};

int main()
{
    /* some code */
    return 0;
}

but the compiler says that :

member 'f' cannot be declared both virtual and static

so I guess the answer is no , but why ?

thanks , Ron

4条回答
在下西门庆
2楼-- · 2019-04-03 01:45

Because the class doesn't have a this pointer. In there is the virtual function lookup table. A quick google can tell you more about the virtual function lookup table.

查看更多
迷人小祖宗
3楼-- · 2019-04-03 01:53

No, static function is like global function, but also inside class namespace. virtual implies inheritance and reimplementing in derived class - you can't reimplement 'global' function.

查看更多
干净又极端
4楼-- · 2019-04-03 01:58

Don't think this is possible because you could call A::F(); without having the object A. Making it virtual and static would mean a contradiction.

查看更多
一夜七次
5楼-- · 2019-04-03 02:01

No. static on a function in a class means that the function doesn't need an object to operate on. virtual means the implementation depends on the type of the calling object. For static there is no calling object, so it doesn't make sense to have both static and virtual on the same function .

查看更多
登录 后发表回答