没有显式指针的C ++多态调用 [英] C++ polymorphic call without explicit pointer

查看:64
本文介绍了没有显式指针的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 ++多态调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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