如何在虚函数的帮助下调用基类show()? [英] How can i call the base class show() withe the help of virtual function?

查看:205
本文介绍了如何在虚函数的帮助下调用基类show()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream.h>
#include <conio.h>

class A
{
      public:
             void show()
             {
                  cout<<"Class A's show()";
             }
};

class B : public A
{
      public:
             void show()
             {
                  cout<<"Class B's show()";
             }
};

int main()
{
    B o;
    o.show();
    getch();
    return 0;
}

推荐答案

虚拟函数对此无济于事(除非您在派生类中调用基类方法). > 但是,由于B A,因此您可以执行以下操作:
Virtual functions won''t help you on that (unless you call the base class method in the derived class one).
However, since B is A you may do:
int main()
{
  B b;
  b.A::show();
}


添加到Cpallini解决方案中,

你可以这样,
Adding to Cpallini solution,

you can do like this,
class B : public A
{
      public:
             void show()
             {
                  cout<<"Class B's show()";
                  A::show();   //call base class show().
             }
};


仅需注意:您没有在派生类中覆盖 show,因为两个函数都不是虚函数,您只需隐藏基类的功能;因此需要CPallini和venkatmakam显示的分辨率.使用 virtual 函数意味着重写的版本将替换派生类的 vtable 中的函数条目.恐怕要说:如果您不了解它,那么您根本不了解OOP.您真的需要学习.

—SA
Just a note: you did not override show in derived class as both functions are not virtual, you have simply hidden the function of the base class; so the resolution shown by CPallini and venkatmakam is needed. Using virtual function means that the overridden version replaces the function entry in the vtable of derived class. I''m afraid to say: if you don''t understand it, you have no idea of OOP — just yet. You really need to learn it.

—SA


这篇关于如何在虚函数的帮助下调用基类show()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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