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

走远了吗. 提交于 2019-12-05 08:23:32

问题


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


回答1:


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 .




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/7227236/can-we-have-a-virtual-static-method-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!