C++继承,虚函数

来源:互联网 发布:数据库保险箱 编辑:程序博客网 时间:2024/06/05 19:04

c++类


c++在继承的时候,会进行函数覆盖.

此时如果用父类指针指向子类的对象,当用指针调用函数的时候,若子类有这样的函数,则调用子类的函数;若子类中没有这个函数,则调用父类的函数,这种称之为迟绑定技术,迟绑定技术构成的多态.

如果父类的函数没有加virtual(而且必须是父类中添加),则会调用父类的函数,这称为早期绑定.

//Animal.h//#ifndef ANIMAL_H_H#define ANIMAL_H_Hclass Animal{public:    Animal(int height,int weight);    Animal(char sex);    Animal();    void eat();    void sleep();    virtual void breathe();//=0;};#endif
//Fish.h//#include "Animal.h"#ifndef FISH_H_H#define FISH_H_Hclass Fish : public Animal{public:    Fish();    Fish(int length);    void breathe();};#endif
//animal.cpp//#include "Animal.h"#include <iostream>using namespace std;Animal::Animal(int height,int weight)//两个参数构造函数{    cout<<"two paras"<<endl;}Animal::Animal(char sex)//一个参数构造函数{    cout<<"one para"<<endl;}Animal::Animal()//默认构造函数{    cout<<"defauclt animal"<<endl;}void Animal::eat(){    cout<<"animal eat"<<endl;}void Animal::sleep(){    cout<<"animal sleep"<<endl;}void Animal::breathe(){    cout<<"aniaml breathe"<<endl;}
//fish.cpp//#include "Fish.h"#include <iostream>using namespace std;Fish::Fish():Animal(300,400)//在构造函数中调用父类的有参构造函数{    cout<<"default construct fish"<<endl;}/*Fish::Fish(int length):Animal('F')//带参构造函数调用父类带参的构造函数{     cout<<"one para construct fish"<<endl;}*/Fish::Fish(int length)//带参构造函数调用父类默认的构造函数{    cout<<"one para construct fish"<<endl;}void Fish::breathe(){    cout<<"fish bubble"<<endl;}
//main.cpp//#include <iostream>#include "Animal.h"#include "Fish.h"void fn(Animal *pAn){    pAn->breathe();}void main(){    Animal a =Animal(200,300);    Animal b=Animal('f');    an.eat();    an.breathe();    Fish fh1;    Fish fh2(4);//fish类继承自animal类,当生成fish的实例fh时,要先执行animal的构造函数,然后执行fish的构造函数    Animal *pAn;    pAn=&fh1;//父类指针指向子类对象    fn(pAn);//输出 fish bubble}

最后输出 fish bubble,如果没加virtual关键词,则会输出animal breath;

编译过程

原创粉丝点击