C++ 基础之虚函数与纯虚函数

虚函数:C++多态的基础,作用可称为晚期绑定或动态绑定。

纯虚函数:可在基类中定义纯虚函数如 :virtual int area() = 0;  // = 0 告诉编译器,函数没有主体,上面的虚函数是纯虚函数。可在子类中继承改写。

#未用到虚函数的早绑定或称早期绑定_start#

#include <iostream>

using namespace std;

class Shape {

protected:

  int width, height;

public:

  Shape( int a=0, int b=0)

    {

    width = a; height = b;

     }

  int area()

    {

    cout << "Parent class area :" <<endl; return 0;

     }

};

class Rectangle: public Shape

{

  public:

     Rectangle( int a=0, int b=0):Shape(a, b) { }

    int area ()

       {

       cout << "Rectangle class area :" <<endl; return (width * height);

      }

};

class Triangle: public Shape

  {

  public: Triangle( int a=0, int b=0):Shape(a, b) { }

      int area ()

        {

         cout << "Triangle class area :" <<endl; return (width * height / 2);

         }

  };

// 程序的主函数

int main( )

   {

  Shape *shape;

  Rectangle rec(10,7);

   Triangle tri(10,5);

  // 存储矩形的地址

   shape = &rec;

  // 调用矩形的求面积函数

  area shape->area();

   // 存储三角形的地址

  shape = &tri;

  // 调用三角形的求面积函数

   area shape->area();

   return 0;

  }

#未用到虚函数的早绑定或称早期绑定_end#

说明:早期绑定不能实现C++的多态,会直接调用基类中的默认的函数,不会根据指针地址调用。

#在上述代码中略作更改#

class Shape

{

   protected:

    int width, height;

   public:

     Shape( int a=0, int b=0)

      {

        width = a; height = b;

       }

    virtual int area()    // 加上虚函数标识 virtual   或者此时可直接改为纯虚函数 :virtual int area() = 0; 省略函数体,=0 是告诉编译器此为纯虚函数,函数具体行为用子类决定。

       {

        cout << "Parent class area :" <<endl; return 0;

      }

};

#此时在调用 main函数,会出现多态,根据不同地址的调用者会出现不同结果#

#虚函数会生成一张虚函数表,编译器根据此表寻找子类中继承者#

posted @ 2022-01-04 15:49  Labant  阅读(85)  评论(0)    收藏  举报