在C++中是否有可能拥有一个static和virtual?的成员函数?显然,没有一种直接的方法(static virtual member();编译错误),但是至少有一种方法可以达到同样的效果吗?
IE:
struct Object
{
struct TypeInformation;
static virtual const TypeInformation &GetTypeInformation() const;
};
struct SomeObject : public Object
{
static virtual const TypeInformation &GetTypeInformation() const;
};
Run Code Online (Sandbox Code Playgroud)
这是有道理的使用GetTypeInformation()上的一个实例(都object->GetTypeInformation())和一类(SomeObject::GetTypeInformation()),它可以为模板,比较有用和重要.
我能想到的唯一方法包括编写两个函数/一个函数和一个常量,每个类,或使用宏.
还有其他方法吗?
可能重复:
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;
}
Run Code Online (Sandbox Code Playgroud)
但是编译器说:
member 'f' cannot be declared both virtual and static
Run Code Online (Sandbox Code Playgroud)
所以我猜答案是否定的,但为什么呢?
谢谢,罗恩
这是一个小测试程序:
#include <iostream>
class Test
{
public:
static void DoCrash(){ std::cout<< "TEST IT!"<< std::endl; }
};
int main()
{
Test k;
k.DoCrash(); // calling a static method like a member method...
std::system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在VS2008 + SP1(vc9)上编译很好:控制台只显示"TEST IT!".
据我所知,不应该在instanced对象上调用静态成员方法.