我们可以有一个虚拟的静态方法吗?(c++)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7227236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can we have a virtual static method ? (c++)
提问by Ron_s
Possible Duplicate:
C++ static virtual members?
可能的重复:
C++ 静态虚拟成员?
Can we have a virtual static method (in C++) ? I've tried to compile the following code :
我们可以有一个虚拟静态方法(在 C++ 中)吗?我试图编译以下代码:
#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
谢谢,罗恩
回答by Michael Anderson
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
.
不static
。在类中的函数上意味着该函数不需要操作对象。virtual
意味着实现取决于调用对象的类型。对于 static 没有调用对象,因此在同一个 function 上同时拥有static
和是没有意义的virtual
。
回答by RvdK
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.
不要认为这是可能的,因为您可以在A::F();
没有对象 A 的情况下进行调用。将其设为虚拟和静态将意味着矛盾。
回答by EnabrenTane
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.
因为这个类没有this
指针。里面有虚函数查找表。一个快速的谷歌可以告诉你更多关于虚函数查找表的信息。
回答by ks1322
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.
不,static
函数就像全局函数,但也在类命名空间内。virtual
暗示在派生类中继承和重新实现 - 您不能重新实现“全局”函数。