没有显式指针的C ++多态调用

编程入门 行业动态 更新时间:2024-10-11 11:18:06
本文介绍了没有显式指针的C ++多态调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我有基础课:

struct Base { void foo() { bar(); } virtual void bar() { } };

和派生类:

struct Derived : public Base { void bar() { cerr << "Derived here\n"; } };

有可能在编写此代码时:

It is happen that when write this code:

Derived d; d.foo();

由于调用了Derived::bar,因此我将看到打印派生于此处".但是我不是通过指向base的指针来调用的,而是在这里工作的多态性.为什么?是因为Base::foo中对bar的调用实际上是对this->bar()的隐式调用,而bar是在类的vtable中找到的?

I will see printing "Derived here" - since Derived::bar was called. But I did not call via pointer to base, but polymorphism working here. Why? Is it because the call to bar in Base::foo is implicitly actually to this->bar() and bar is finding in vtable of class?

推荐答案

您的猜测是正确的(尽管请记住,C ++标准对vtable没有任何说明).

Your guess is precisely correct (although bear in mind that the C++ standard says nothing about vtables).

更多推荐

没有显式指针的C ++多态调用

本文发布于:2023-11-05 03:08:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1559743.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   多态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!