首页 > 编程语言 > 详细

c++继承

时间:2019-09-01 23:51:51      阅读:132      评论:0      收藏:0      [点我收藏+]
#include<iostream> 
using namespace std;

class Biological{
public:
    virtual void range(){
        cout<<"widely"<<endl;
    }

    void name(){
        cout<<"biological"<<endl;
    }
};

class Animal:public Biological{
public:
    virtual void range(){
        cout<<"medium"<<endl;
    }

    void name(){
        cout<<"animal"<<endl;
    }
};

class Person:public Animal{
public:
    virtual void range(){
        cout<<"small"<<endl;
    }

    void name(){
        cout<<"person"<<endl;
    }
};

void Display(Biological *p){
    p->range();
    p->name();
    delete p;
}

int main(){
    Display(new Biological);
    Display(new Animal);
    Display(new Person);
    return 0;
}

技术分享图片

#include<iostream> 
using namespace std;

class Biological{
public:
    Biological(){
        cout<<"Biological构造"<<endl; 
    }

    ~Biological(){
        cout<<"Biological析构"<<endl; 
    }
};

class Animal:virtual public Biological{
public:
    Animal(){
        cout<<"Animal构造"<<endl; 
    }

    ~Animal(){
        cout<<"Animal析构"<<endl; 
    }
};

class Plant:virtual public Biological{
public:
    Plant(){
        cout<<"Plant构造"<<endl; 
    }

    ~Plant(){
        cout<<"Plant析构"<<endl; 
    }
};

class SeaAnemone:public Animal,public Plant{
public:
    SeaAnemone(){
        cout<<"SeaAnemone构造"<<endl; 
    }

    ~SeaAnemone(){
        cout<<"SeaAnemone析构"<<endl; 
    }
};


int main(){
    SeaAnemone sea_anemone;
    return 0;
}

技术分享图片

#include<iostream> 
using namespace std;

class Biological{
public:
    Biological(){
        cout<<"Biological构造"<<endl; 
    }

    virtual ~Biological(){
        cout<<"Biological析构"<<endl; 
    }
private:
    char *name;
};

class Animal:virtual public Biological{
public:
    Animal(){
        cout<<"Animal构造"<<endl; 
    }

    ~Animal(){
        cout<<"Animal析构"<<endl; 
    }
};

class Plant:virtual public Biological{
public:
    Plant(){
        cout<<"Plant构造"<<endl; 
    }

    ~Plant(){
        cout<<"Plant析构"<<endl; 
    }
};

class SeaAnemone:public Animal,public Plant{
public:
    SeaAnemone(){
        cout<<"SeaAnemone构造"<<endl; 
    }

    ~SeaAnemone(){
        cout<<"SeaAnemone析构"<<endl; 
    }
};


int main(){
    Biological *sea_anemone = new SeaAnemone;
    delete sea_anemone;
    return 0;
}

技术分享图片

注意:如果将~Biological()函数前的virtual去掉那么函数会出错。

总结:我们一定要注意在基类的析构函数前面加上virtual,使其变成虚析构在C++程序中使用虚函数,虚继承和虚析构是很好的习惯 可以避免许多的问题。

c++继承

原文:https://www.cnblogs.com/ligei/p/11443857.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!