zoukankan      html  css  js  c++  java
  • 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(){}
    	
    };
    

     结果为:

     

  • 相关阅读:
    【转】对象持久化与数据序列化的联系?
    【转】Linux安装方法一(U盘引导)
    bash中的"-n"、"-z" 以及“[]” 、“[[]]”判断
    mysql获取行号
    IP白名单
    复合赋值位运算符“&=、| =”
    Java匿名内部类访问外部
    mysql的orde by 按照指定状态顺序排序
    Spring声明式事务
    定时任务总结
  • 原文地址:https://www.cnblogs.com/anlia/p/9083877.html
Copyright © 2011-2022 走看看