子类和父类的构造函数

子类与父类的构造函数  

2008-11-07 18:13:17|  分类: c/c++ |  标签: |字号 订阅

 
 

先看下面的例子:
    #include <iostream.h>
    class animal
    {
    public:
         animal(int height, int weight)
         {
             cout<<"animal construct"<<endl;
         }
         ~animal()
         {
             cout<<"animal destruct"<<endl;
         }
         void eat()
         {
             cout<<"animal eat"<<endl;
         }
         void sleep()
         {
             cout<<"animal sleep"<<endl;
         }
         void breathe()
         {
             cout<<"animal breathe"<<endl;
         }
    };
    class fish:public animal
    {
    public:
         fish()
         {
             cout<<"fish construct"<<endl;
         }
         ~fish()
         {
             cout<<"fish destruct"<<endl;
         }
    };
    void main()
    {
         fish fh;
    }

当我们构造fish子类的对象fh时,它需要先构造anima父l类的对象,调用anima父l类的默认构造函数(即不带参数的构造函数),而在我们的程序中,animal类只有一个带参数的构造函数,在编译时,编译器会自动产生一个不带参数的animal父类构造函数作为默认的构造函数。

在子类构造函数中想要调用父类有参数的构造函数(或子类要向父类的构造函数传递参数)时,就必须显式的指明需要调用的是哪一个父类构造函数。具体方法是:子类构造函数应当这样声明  子类名::子类名(参数):父类名(参数);
可以采用如下例子所示的方式,在构造子类时,显式地去调用父类的带参数的构造函数,而父类无参数的构造函数则不再调用。

#include <iostream.h>
    class animal
    {
    public:
        animal(int height, int weight)
        {
            cout<<"animal construct"<<endl;
        }
        …
    };
    class fish:public animal
    {
    public:
        fish():animal(400,300)
        {
            cout<<"fish construct"<<endl;
        }
        …
    };
    void main()
    {
        fish fh;
    }

此外还可以使用this指针来调用父类有参数的构造函数,具体做法如下代码:

#include <iostream.h>
    class animal
    {
    public:
        animal(int height, int weight)
        {
            cout<<"animal construct"<<endl;
        }
        …
    };
    class fish:public animal
    {
    public:
        fish()
        { 
            this->animal ::animal (400,300);
        }
        …
    };
    void main()
    {
        fish fh;
    }

这在子类化一些抽象类的时候很有帮助,今天一整天的收获还不错。

一切源于对计算机的热爱
原文地址:https://www.cnblogs.com/liuweilinlin/p/2639450.html