虚拟函数对象切片 [英] Virtual Functions Object Slicing

查看:98
本文介绍了虚拟函数对象切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是参考此问题,其中解释了虚拟函数在对象切片的情况下工作,最终调用基类虚拟函数和维基百科文章,其解释虚拟下面代码的派生类的表格布局

My question is with reference to this question which explains how virtual functions work in case of object slicing which end up calling base class virtual function and Wikipedia article which explains the virtual table layout for a derived class for below code

    class A{

    public:
     virtual void func(){ cout<<"\n In A:func";}
    };

    class B:public A{

    public:
     virtual void func(){ cout<<"\n In B:func";}
    };

   main(){
    A *ptr1 = new B();

    A oA = *ptr1;

    oA.func(); 
  }




      DerviedClassObjectB:
         +0: pointer to virtual method table of B 

       virtual method table of B:
         +0: B::func

A :: func。

Above program outputs "In A::func" .

但是没有虚拟表的B类知道基类A :: func结束了调用A :: func

But how does without virtual table for class B knowing about base class A::func ends up calling A::func

推荐答案

B 的虚拟表? oA.func()调用不涉及 B 的虚表。对象 oA 有类型 A ,这意味着其虚拟表是 / code>。

"Virtual table for class B"? Virtual table for class B is not involved in oA.func() call at all. Object oA has type A, which means that its virtual table is that of class A.

此外,大多数编译器将优化 oA.func()它不会使用任何虚拟表。因为 oA 的类型在编译时是已知的,所以 oA.func()调用可以立即被指向 A :: func ,而不使用任何虚拟表。

Moreover, most compilers will optimize the oA.func() call so that it won't use any virtual tables at all. Since the type of oA is known at compile time, the oA.func() call can be immediately directed to A::func without using any virtual tables.

这篇关于虚拟函数对象切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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