为什么对派生类使用基类指针

Why use base class pointers for derived classes(为什么对派生类使用基类指针)

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

问题描述

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?

}

我不是 CompSci 工程师,我想知道这一点.如果我们可以避免基类指针,为什么还要使用虚函数?

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.

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

本文标题为:为什么对派生类使用基类指针

基础教程推荐