zoukankan      html  css  js  c++  java
  • 虚函数和纯虚函数

    #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(),否则编译器会报错;

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

  • 相关阅读:
    Hive_MySQL安装
    Hive_安装部署
    Hive_和关系数据库比较
    Hive_架构原理
    Hive_优缺点
    Hive_什么是Hive
    java中的编码规范(1)
    SpringBoot_常用注解
    什么是WebMvcConfigurer
    什么是大数据倾斜
  • 原文地址:https://www.cnblogs.com/ITGUANCHAZHE/p/14319719.html
Copyright © 2011-2022 走看看