我们可以有一个虚拟的静态方法吗? (C ++) [英] Can we have a virtual static method ? (c++)

查看:84
本文介绍了我们可以有一个虚拟的静态方法吗? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C ++静态虚拟成员?

我们可以有一个虚拟静态方法吗? (在C ++中)?我尝试编译以下
代码:

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;
}

但是编译器说:

member 'f' cannot be declared both virtual and static

所以我想答案是否定的,但是为什么呢?

so I guess the answer is no , but why ?

谢谢,
罗恩

推荐答案

不。对类中的函数进行 static 表示该函数不需要操作对象。 virtual 表示实现取决于调用对象的类型。对于静态对象,没有调用对象,因此将 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 both static and virtual on the same function .

这篇关于我们可以有一个虚拟的静态方法吗? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆