我们可以有一个虚静态方法吗? (c++)
可能的重复:
C++ 静态虚拟成员?
我们可以有一个虚拟静态方法(在 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;
}
但编译器说:
member 'f' cannot be declared both virtual and static
所以我猜答案是否定的,但为什么呢?
谢谢 , 罗恩
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不。类中函数的
static
意味着该函数不需要对象来操作。虚拟
意味着实现取决于调用对象的类型。对于 static 来说,没有调用对象,因此在同一个函数上同时使用static
和virtual
是没有意义的。
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 bothstatic
andvirtual
on the same function.
不要认为这是可能的,因为您可以在没有对象 A 的情况下调用
A::F();
。使其虚拟和静态意味着矛盾。
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.
不,
static
函数就像全局函数,但也在类命名空间内。virtual
意味着在派生类中继承和重新实现 - 您无法重新实现“全局”函数。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.因为该类没有
this
指针。里面有虚函数查找表。快速谷歌一下可以告诉你更多关于虚函数查找表的信息。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.