派生类的构造函数的初始化

1.若基类的构造函数不带参数,则派生类的构造函数也不需要带参数,并且可用默认构造函数。

  若基类的构造函数带参数,则派生类的构造函数有一定的形式:

  

 1 #include<iostream>
 2 using namespace std;
 3 class Animal
 4 {
 5     public:
 6     Animal(int height,int weight)//带参数的构造函数
 7     {
 8        cout<<"Animal construct."<<endl;
 9     }
10     virtual void breathe()//虚函数
11     {
12       cout<<"Animal breathe."<<endl;
13     }
14     ~Animal()//析构函数
15     {
16       cout<<"Animal deconstruct."<<endl;
17     }
18 };
19 class Fish:public Animal//Fish类继承Animal类,注意类名一般大写
20 {
21     public:
22     Fish():Animal(400,300)//派生类构造函数,若基类的构造函数带参数,则必须加上
23     {
24       cout<<"Fish construct."<<endl;
25     }
26     void breathe()
27     {
28 //      Animal::breathe();
29       cout<<"Fish bubble"<<endl;
30     }
31     ~Fish()
32     {
33       cout<<"Fish deconstruct."<<endl;
34     }
35 };
36 void fun(Animal *pAn)
37 {
38     pAn->breathe();
39 }
40 void main()
41 {  
42     Animal *pAn=new Animal(80,50);//Animal对象的初始化,必须带参数
43     pAn->breathe();
44     delete pAn;//注意new出来的对象一定要delete掉,否则会发生内存泄漏
45     Fish *f=new Fish();
46     Animal *pm=f;
47     fun(pm);//传入的参数是fish类的
48     delete f;    
49     system("pause");
50 }

2. 运行结果

 代码分析:在构造Fish类对象f的时候,可以看到Animal的构造函数又执行了一遍,并且是先构造Animal的,再构造Fish的。

               同样的,在delete f的时候先调用Fish的析构函数,再是Animal的析构函数,即先构造的后析构。

               

原文地址:https://www.cnblogs.com/dongyanxia1000/p/4905488.html