没有指针或引用的c ++虚函数调用 [英] c++ virtual function call without pointer or reference

查看:55
本文介绍了没有指针或引用的c ++虚函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,虚函数调用通常需要指针或引用.所以我对以下代码感到非常惊讶.

As far as I know, virtual function call usually requires pointer or reference. So I am very surprised by the following codes.

#include <iostream>
using namespace std;
class B{
public:
  void runB(){        call();  }
  virtual void call(){ cout<<"B\n"; };
};

class D: public B{
public:
  void runD(){       runB();   }
  void call(){       cout<<"D\n";  }
};

int main(){
 D d;
 d.runD();
}

输出为

D

有人可以评论为什么这个虚函数调用有效吗?谢谢.

Could someone please comment why this virtual function call works? Thanks。

推荐答案

在成员函数内,对其他成员函数或变量的任何引用都通过 this 指针隐式解析.所以在 runB() 的定义中,call() 的意思是 this->call().使用当前对象的虚拟表执行虚拟函数调用.

Within a member function, any references to other member functions or variables are implicitly resolved via the this pointer. So in the definition of runB(), the call() really means this->call(). The virtual function call is performed using the current object's virtual table.

这篇关于没有指针或引用的c ++虚函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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