关于名称隐藏和虚函数的混淆 [英] Confusion regarding name hiding and virtual functions

查看:56
本文介绍了关于名称隐藏和虚函数的混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用另一个 所以问题

考虑代码:

class Base {
public: 
    virtual void gogo(int a){
        printf(" Base :: gogo (int) \n");
    };

    virtual void gogo(int* a){
        printf(" Base :: gogo (int*) \n");
    };
};

class Derived : public Base{
public:
    virtual void gogo(int* a){
        printf(" Derived :: gogo (int*) \n");
    };
};

int main(){

    // 1)       
    Derived * obj = new Derived ; 
    obj->gogo(7);  // this is illegal because of name hiding


    // 2)      
    Base* obj = new Derived ;
    obj->gogo(7); // this is legal
}

对于情况 2)

调用 obj->gogo(7) 在运行时解析.

The call obj->gogo(7) is resolved at run time.

因为 obj->gogo(7) 是合法的.似乎暗示 Derived 的 vtable 包含指向virtual void gogo(int a) 本应隐藏.

Since obj->gogo(7) is legal. It seems to imply that vtable of Derived contains ptr to virtual void gogo(int a) which should have been hidden.

我的困惑是,由于名称隐藏导致 case 1) 非法,那么如何在运行时解析 2) 中的调用

My confusion is , since name hiding causes case 1) to be illegal, then how the call in 2) is resolved at run time

a) Derived 的 vtable 是否包含指向 gogo(int) 的指针.

a) Does vtable of Derived contains pointer to gogo(int).

b) 如果 a) 不为真,虚函数的调用解析是否继续到基类的 vtable.

b) If a) is not True, Does call resolution for virtual functions proceeds to vtable of base class.

推荐答案

你混淆了虚函数调用和重载解析.

You are confusing virtual functions calls and overload resolution.

所有派生类都有包含所有虚函数的虚表,来自基类和任何额外的自己的虚函数.这用于在运行时解析调用,例如您的情况 2).

All derived classes have vtables containing all virtual functions, from the base class and any additional own virtual functions. This is used to resolve calls at runtime, like in your case 2).

如果 1) 您在编译时从重载解析中得到错误.由于名称隐藏,Derived 类只有一个可调用函数.您唯一的选择是使用 int* 调用该函数.

In case 1) you get an error from overload resolution at compile time. Due to name hiding, class Derived only has one callable function. Your only choice is to call that function, with an int*.

这篇关于关于名称隐藏和虚函数的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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