运行时检查实例(Base *)是否覆盖父函数(Base :: f()) [英] runtime-check whether an instance (Base*) override a parent function (Base::f())
问题描述
如何确定基类( B
)的指针是否(多态)覆盖基类的某个虚函数?
How to determine whether a pointer of base (B
) class is (polymorphism-ly) override a certain virtual function of the base class?
class B{
public: int aField=0;
virtual void f(){};
};
class C : public B{
public: virtual void f(){aField=5;};
};
class D: public B{};
int main() {
B b;
C c;
D d;
std::vector<B*> bs;
bs.push_back(&b);
bs.push_back(&c);
bs.push_back(&d);
for(int n=0;n<3;n++){
//std::cout<<(bs[n]->f)==B::f<<std::endl;
//should print "true false true"
}
}
我试图将函数指针 bs [n]-> f
的地址与 B :: f
进行比较,但无法编译。
I tried to compare the address of function pointer bs[n]->f
against B::f
, but it is uncompilable.
我觉得这个问题可能重复了,但我找不到(抱歉)。
I feel that this question might be duplicated, but I can't find (sorry).
推荐答案
GCC具有扩展名,该扩展名允许您获取虚拟成员函数的地址。
GCC has an extension that allows you to get the address of a virtual member function.
可以这样使用:
#include <vector>
#include <iostream>
class B{
public: int aField=0;
virtual void f(){};
};
class C : public B{
public: virtual void f(){aField=5;};
};
class D: public B{};
int main() {
B b;
C c;
D d;
std::vector<B*> bs;
bs.push_back(&b);
bs.push_back(&c);
bs.push_back(&d);
for(int n=0;n<3;n++){
// This might need to be: (void*) B{}.*&B::f == (void*) (...)
std::cout << ((void*) &B::f == (void*)(bs[n]->*&B::f)) << '\n';
}
}
您可能会发现此质量检查很有趣。
自然地,这是非标准行为。如果您希望在标准C ++中具有类似的行为,则实际上可能正在寻找纯虚拟函数:
Naturally, this is nonstandard behavior. If you wanted similar behavior in standard C++, you might actually be looking for pure virtual functions:
class B{
public: int aField=0;
virtual void f() = 0;
};
否则,您必须具有一些其他通信机制,例如 bool
返回类型为 f()
。
Otherwise, you'd have to have some other mechanism to communicate, such as a bool
return type on f()
.
这篇关于运行时检查实例(Base *)是否覆盖父函数(Base :: f())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!