首页 > 其他 > 详细

构造函数的继承

时间:2020-03-31 10:50:59      阅读:58      评论:0      收藏:0      [点我收藏+]

首先我们有一个父类

class Father
{
public:
    Father(int tall);
    int tall;    
    void fuc();
};

Father::Father(int tall)
{
    this->tall = tall;
}

void Father::fuc()
{
    cout<<"height is "<<tall<<endl;
}

父类里面有显式的构造函数 和 一个成员函数 fuc

 

然后再来看子类

class Child:public Father
{
public:
    Child(int tall);

};

Child::Child(int tall):Father(tall)
{

}

 

在主函数中调用一下

    Child tom(200);
    tom.fuc();

运行结果

height is 200

表明子类已经成功继承了父类的构造函数 同时还调用了继承过来的变量 tall 以及成员函数 fuc

 


 

 

还有另外一种写子类的方法

class Child:public Father
{
    using Father::Father;
public:
    
};

using 父类::父类

当构造函数重载比较多时,这样方便很多

 

 

全部代码如下

class Father
{
public:
    Father(int tall);
    int tall;    
    void fuc();
};

Father::Father(int tall)
{
    this->tall = tall;
}

void Father::fuc()
{
    cout<<"height is "<<tall<<endl;
}


class Child:public Father
{
    using Father::Father;
public:
    
};



int main(int argc,char *argv[])
{
    Child tom(200);
    tom.fuc();

    return 0;
}

 

构造函数的继承

原文:https://www.cnblogs.com/qifeng1024/p/12603010.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!