虚函数对象切片

发布于 2024-09-14 10:10:48 字数 776 浏览 6 评论 0原文

我的问题是参考这个问题,它解释了虚拟函数在情况下如何工作对象切片最终调用基类虚函数和维基百科文章解释了虚拟表布局对于以下代码的派生类

    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

上面的程序输出“In A::func”。

但是,如果类 B 的虚表不知道基类 A::func,那么如何最终调用 A::func

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

Above program outputs "In A::func" .

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

勿忘初心 2024-09-21 10:10:48
A oA = *ptr1;

这会将所有成员变量复制到新的 A 对象中。 vtable 指针不是普通的成员变量,并且不会被复制。因此,针对该对象调用的任何后续虚拟函数都将表现为它是一个 A 对象,因为它一个 A 对象。

A oA = *ptr1;

This copies any member variables into a new A object. The vtable pointer is not a normal member variable and is not copied. Thus any subsequent virtual functions called against this object will act as if it is an A object, because it is an A object.

巴黎盛开的樱花 2024-09-21 10:10:48

B 类的虚拟表”? B 类的虚拟表根本不参与 oA.func() 调用。对象oA 具有类型A,这意味着它的虚拟表是类A 的虚拟表。

此外,大多数编译器都会优化 oA.func() 调用,以便它根本不会使用任何虚拟表。由于 oA 的类型在编译时已知,因此 oA.func() 调用可以立即定向到 A::func,而无需使用任何虚拟表。

"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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文