为什么要使用派生类的基类指针 [英] Why use base class pointers for derived classes

查看:160
本文介绍了为什么要使用派生类的基类指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class base{
    .....
    virtual void function1();
    virtual void function2();
};

class derived::public base{
    int function1();
    int function2();
};

int main()
{
    derived d;
    base *b = &d;
    int k = b->function1() // Why use this instead of the following line?
    int k = d.function1(); // With this, the need for virtual functions is gone, right?

}

对不起,一个noobish问题,但我不是一个CompSci工程师我想知道这一点。为什么要使用虚拟函数,如果我们可以避免基类指针?

Sorry for a noobish question but I am not a CompSci engineer and I would like to know this. Why use virtual functions if we can avoid base class pointers?

推荐答案

多态性的力量在你的简单示例

The power of polymorphism isn't really apparent in your simple example, but if you extend it a bit it might become clearer.

class vehicle{
      .....
      virtual int getEmission();
 }

 class car : public vehicle{
      int getEmission();
 }

 class bus : public vehicle{
      int getEmission();
 }

 int main()
 {
      car a;
      car b;
      car c;
      bus d;
      bus e;

      vehicle *traffic[]={&a,&b,&c,&d,&e};

      int totalEmission=0;

      for(int i=0;i<5;i++)
      {
          totalEmission+=traffic[i]->getEmission();
      }

 }

的指针,并根据底层类型调用不同的方法。基本上,它允许你编写代码,你不需要知道子类型是在编译时,但代码将执行正确的函数。

This lets you iterate through a list of pointers and have different methods get called depending on the underlying type. Basically it lets you write code where you don't need to know what the child type is at compile time, but the code will perform the right function anyway.

这篇关于为什么要使用派生类的基类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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