• C++类继承--继承后函数的值


    类的继承会首先寻找基类,若基类未实现,则会寻找派生类的函数

    1. class继承,函数不继承

    #include <stdio.h>
    
    class Base
    {
    public:
    	Base(){}
    	~Base(){}
    
    	int a;
    	void setA()
    	{
    		a  = 1;
    	}
    };
    
    class A:public Base
    {
    public:
    	A(){}
    	~A(){}
    	
    	void setA()
    	{
    		a  = 2;
    	}
    	
    };
    
    class B:public Base
    {
    public:
    	B(){}
    	~B(){}
    	
    	void setA()
    	{
    		a = 3;
    	}
    };
    
    int main()
    {
    	A *ax = new A();
    	B *bx = new B();
    	Base *aClass =  ax;
    	Base *bClass = bx;
    	aClass->setA();
    	bClass->setA();
    
    	printf("a value of a %d
    ", aClass->a);
    	printf("a value of b %d
    ", bClass->a);
    	return 0;
    }
    

      运行结果:

    2. 函数和Class都继承

    #include <stdio.h>
    
    class Base
    {
    public:
    	Base(){}
    	~Base(){}
    
    	int a;
    	virtual void setA()
    	{
    		a  = 1;
    	}
    };
    
    class A:public Base
    {
    public:
    	A(){}
    	~A(){}
    	
    	virtual void setA()
    	{
    		a  = 2;
    	}
    	
    };
    
    class B:public Base
    {
    public:
    	B(){}
    	~B(){}
    	
    	virtual void setA()
    	{
    		a = 3;
    	}
    };
    
    int main()
    {
    	A *ax = new A();
    	B *bx = new B();
    	Base *aClass =  ax;
    	Base *bClass = bx;
    	aClass->setA();
    	bClass->setA();
    
    	printf("a value of a %d
    ", aClass->a);
    	printf("a value of b %d
    ", bClass->a);
    	return 0;
    }
    

      运行结果:注意派生类中可以不写virtual,最好写上,以辨别是函数继承

      若将2中基类的函数写为纯虚函数,运行的结果一样,但是如果基类是纯虚函数,派生类必须实现相应的函数。

    class Base
    {
    public:
    	Base(){}
    	~Base(){}
    
    	int a;
    	virtual void setA()=0;
    	
    };
    

      

    3. 类A中不有函数,则继承自基类

    class A:public Base
    {
    public:
    	A(){}
    	~A(){}
    	
    };
    

     结果为:

     

  • 相关阅读:
    Java 反射机制
    Hibernate学习
    js学习
    如何在jsp中引入bootstrap
    bootstrap学习一
    第二章、初级篇
    定风波
    Java反射机制
    数据库的优化方法
    MySQL常用的查询语句回顾
  • 原文地址:https://www.cnblogs.com/anlia/p/9083877.html
Copyright © 2020-2023  润新知