在C++中子类继承和调用父类的构造函数方法

构造方法用来初始化类的对象,与父类的其它成员不同,它不能被子类继承(子类可以继承父类所有的成员变量和成员方法,但不继承父类的构造方法)。因此,在创建子类对象时,为了初始化从父类继承来的数据成员,系统需要调用其父类的构造方法

2.如果没有显式的构造函数,编译器会给一个默认的构造函数,并且该默认的构造函数仅仅在没有显式地声明构造函数情况下创建。

 

3.如果子类调用父类带参数的构造方法,需要用初始化父类成员对象的方式.

办法1:

#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;  
 }  
  在fish类的构造函数后,加一个冒号(:),然后加上父类的带参数的构造函数。这样,在子类的构造函数被调用时,系统就会去调用父类的带参数的构造函数去构造对象。

办法二:

使用using来继承基类构造函数 。具体参考:c++11中using的使用_baidu_16370559的博客-CSDN博客

#include <iostream>
using namespace std;

class Base
{
public:
    Base(int a, int b, int c)  //有且仅有 有参参数,必须显性调用
    {
        m_a = a;
        m_b = b;
        m_c = c;
        cout << "父类的构造函数m_a :" << m_a << endl;
    }
public:
    int m_a;
    int m_b;
    int m_c;
};
 
class Child : public Base
{
public:
    //子类继承父类构造方法
    using Base::Base;
};
 
int main()
{
    //子类继承父类构造方法创建对象
    Child ch1(1, 2, 3);
    return 0;
};

更进一步

#include <iostream>
using namespace std;
 
class Base
{
public:
    Base(int a, int b, int c)
    {
        m_a = a;
        m_b = b;
        m_c = c;
        cout << "父类的构造函数m_a :" << m_a << endl;
    }
public:
    int m_a;
    int m_b;
    int m_c;
};
 
class Child : public Base
{
public:
    //子类继承父类构造方法
    using Base::Base;

 
    //子类委托父类构造方法
    Child(int a, int b, int c, double d) : Base(a, b, c)

    {
        m_d = d;
        cout << "子类的构造函数m_d :" <<  m_d << endl;
    }
 
    double m_d;
};
 
int main()
{
    //子类继承父类构造方法创建对象
    Child ch1(1, 2, 3);
    cout << "----------------------------" << endl;
    //子类委托父类构造方法创建对象
    Child ch(4, 5, 6, 7.7);

    return 0;
};

  • 10
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值