#include <iostream>
using namespace std;

class A
{
public:
	void fun()
	{
		cout<<"This is A::fun()."<<endl;
	}
    virtual void fun1()        //虚函数,基类和子类都可以实现。
    {
        cout<<"This is A::fun1()."<<endl;
    }
	virtual void fun2()= 0;    //纯虚函数,基类不用实现,子类必须实现。
};
class B:public A
{
public:
	void fun()
	{
		cout<<"This is B::fun()."<<endl;
	}
    void fun1()
    {
        cout<<"This is B::fun1()."<<endl;
    }
	void fun2()
    {
        cout<<"This is B::foo2()."<<endl;
    }
};
int main(void)
{
    A *a = new B();
	a->fun();
    a->fun1();  
	a->fun2(); 
	delete a;
    return 0;
}

结果如下:

This is A::fun().
This is B::fun1().
This is B::foo2().

如果B类不实现fun1(),则a->fun1() 调用的是A类的fun1();

B类必须实现fun2(),否则编译器会报错;

使用纯虚函数函数,统一函数接口;

posted on 2020-12-22 09:17  IT观察者  阅读(59)  评论(0编辑  收藏  举报