码迷,mamicode.com
首页 > 其他好文 > 详细

继承的构造函数

时间:2018-02-10 14:07:31      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:turn   iic   重用   访问   定义   多个   ase   names   ace   

在C++11新标准中,派生类能够重用其直接基类的构造函数

#include <iostream>
using namespace std;

struct Base
{
    Base() { cout << "construct" << endl; }
};
struct Derived : public Base
{
    using Base::Base; //继承Base的构造函数
};

int main()
{
    Derived d;
    return 0;
}

一个构造函数的声明不会改变该函数的访问级别

#include <iostream>
using namespace std;

struct Base
{
    Base() { cout << "construct" << endl; }
};
struct Derived : public Base
{
   private://不会改变继承的构造函数的访问级别,仍然是publiic
     using Base::Base; 
};

int main()
{
    Derived d;
    return 0;
}

当一个基类的构造函数含有默认实参,这些实参并不会被继承。相反,派生类将获得多个继承的构造函数

#include <iostream>
using namespace std;

struct Base
{
    Base(int x=1) { cout << "construct" <<x<< endl; }
};
struct Derived : public Base
{
    //实际上继承了2个构造函数
     using Base::Base; 
};

int main()
{
    Derived d;
    Derived d1(2);
    return 0;
}

如果派生类定义的构造函数与基类的构造函数有相同的参数列表,该构造函数不会被继承

#include <iostream>
using namespace std;

struct Base
{
    Base() { cout << "construct" << endl; }
    Base(int) { cout << "construct int" << endl; }
};
struct Derived : public Base
{

    using Base::Base;
    //不会继承Base的默认构造函数
    Derived() { cout << "Derived class construct" << endl; };
};

int main()
{
    Derived d;
    Derived d(1);
    return 0;
}

继承的构造函数

标签:turn   iic   重用   访问   定义   多个   ase   names   ace   

原文地址:https://www.cnblogs.com/lkpp/p/cpp-derived-construct.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!