我如何确定是否在编译时覆盖了一个函数

How can I determine whether a function was overridden at compile time?

本文关键字:函数 一个 覆盖 何确定 是否 编译      更新时间:2023-10-16

也许是一个愚蠢的问题。

假设我有以下内容:

class A{
     int x;
     int y;
     virtual int get_thing(){return x;}
};
class B : public A {
     int get_think(){return y;}
};

在上面的示例中,b :: get_thing返回x,因为覆盖代码具有错字。

我如何确保在编译时间在B类中覆盖get_thing函数以返回y?

假设A::get_thing是虚拟的,并且假设class B是从class A派生的,并且您具有C 11支持,则可以使用override特殊标识符:

class B : public A{
     int get_think() override {return y;}
};

这将产生编译器误差。请注意,这是基于该方法的签名,即其名称,简历预选赛和参数类型。返回类型或功能的主体未进入。

首先,您在示例中有一个错误,我认为B应该是A的孩子,不是吗?!

,但答案是:您可以比较功能的地址(当然,如果您愿意,并且在编程时间无法检查):

if( reinterpret_cast<void*>(&B::get_think) != reinterpret_cast<void*>(&A::get_think) ) {
    std::cout << "B override A";
} else {
    std::cout << "B override A";
}
相关文章: