zoukankan      html  css  js  c++  java
  • 子类和父类的构造函数

    子类与父类的构造函数  

    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;
        }

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

    一切源于对计算机的热爱
  • 相关阅读:
    LIKE谓词
    [C#网络编程系列]专题一:网络协议简介
    (zz)Sql Server 2005中的架构(Schema)、用户(User)、角色(Role)和登录(Login)(三)
    zz让你成功的九个心理定律
    zz给 VSTO 插件、文档传送参数
    重构笔记
    (zz)Sql Server 2005中的架构(Schema)、用户(User)、角色(Role)和登录(Login)(二)
    zzVSTO 先瘦身再发布:客户端配置文件
    zz将 VSTO 插件部署给所有用户
    (zz)Sql Server 2005中的架构(Schema)、用户(User)、角色(Role)和登录(Login)(一)
  • 原文地址:https://www.cnblogs.com/liuweilinlin/p/2639450.html
Copyright © 2011-2022 走看看