C ++静态虚拟成员? [英] C++ static virtual members?
问题描述
有可能在C ++中有一个成员函数 static
和 virtual
?显然,没有一个简单的方法来做它( static virtual member();
是一个编译错误),但是至少有一种方法来实现相同的效果?
Is it possible in C++ to have a member function that is both static
and virtual
? Apparently, there isn't a straightforward way to do it (static virtual member();
is a compile error), but is there at least a way to achieve the same effect?
IE:
struct Object
{
struct TypeInformation;
static virtual const TypeInformation &GetTypeInformation() const;
};
struct SomeObject : public Object
{
static virtual const TypeInformation &GetTypeInformation() const;
};
使用 GetTypeInformation()
( object-> GetTypeInformation()
)和类( SomeObject :: GetTypeInformation()
),它可以用于比较和模板的重要性。
It makes sense to use GetTypeInformation()
both on an instance (object->GetTypeInformation()
) and on a class (SomeObject::GetTypeInformation()
), which can be useful for comparisons and vital for templates.
我可以想到的唯一方法包括写两个函数/一个函数和一个常量,每个类,
The only ways I can think of involves writing two functions / a function and a constant, per class, or use macros.
任何其他解决方案?
推荐答案
没有办法做,因为当你调用 Object :: GetTypeInformation()
会发生什么?它不能知道要调用哪个派生类版本,因为没有与它相关联的对象。
No, there's no way to do it, since what would happen when you called Object::GetTypeInformation()
? It can't know which derived class version to call since there's no object associated with it.
您必须将其作为非静态虚函数才能正常工作;如果你还想要在没有对象实例的情况下非虚拟地调用一个特定的派生类的版本,你必须提供第二个redunduant静态非虚拟版本。
You'll have to make it a non-static virtual function to work properly; if you also want to be able to call a specific derived class's version non-virtually without an object instance, you'll have to provide a second redunduant static non-virtual version as well.
这篇关于C ++静态虚拟成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!