六:多态性和虚函数

6.1:虚函数和纯虚函数

(1)什么是虚函数,作用?

虚函数是大多是为了实现动态链接,父类指针变量指向基类的指针,调用自己的方法。虚函数目的就是为了基类用来实现多态性。

2)纯虚函数和虚函数有什么区别?

  纯虚函数:纯虚函数是抽象类的表示,类似公有接口的编写。纯虚函数用于抽象类,本身是不能生成对象的。

 虚函数是纯虚函数的一个子集。

 纯虚函数声明:

 virtual void area( int i, int j ) = 0; 纯虚函数

示例代码:
#include<iostream>
using namespace std;

class A{
  public:
    A( int a1,int b1 )
    {
      this->a = a1;
      this->b = b1;
    };
    ~A(){};
  virtual void show();
  public:
    int a;
    int b;
};

 void A::show()
{
  cout<<this->a<<"  "<<this->b<<endl;
}


class B:public A{
  private:
    int c;
  public:
    B( int a1, int b1, int c1):A(a1,b1),c(c1){};
    ~B(){};
    virtual void show();
};

void B::show(){
    cout<<this->a<<"  "<<this->b<<"  "<<this->c<<endl;
}


int main(void)
{
   A a(1,2),*p;
   B b(3,4,5);

   p = &a;
   p->show(); //多态性

   p=&b;
   p->show(); //多态性
}
原文地址:https://www.cnblogs.com/love-life-insist/p/12831598.html