继承的构造函数

在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://不会改变继承的构造函数的访问级别,仍然是public
     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;
}
posted @ 2018-02-10 12:09  ,,,沙子,,,  阅读(228)  评论(0)    收藏  举报
编辑推荐:
· 协程本质是函数加状态机——零基础深入浅出 C++20 协程
· 编码之道,道心破碎。
· 记一次 .NET 某发证机系统 崩溃分析
· 微服务架构学习与思考:SOA架构与微服务架构对比分析
· tomcat为什么假死了
阅读排行:
· 知名开源项目Alist被收购!惹程序员众怒,开团炮轰甲方
· 突发,小红书开发者后门被破解?!
· 历时半年,我将一个大型asp.net的零代码快速开发平台转成了java
· Windows11 关闭搜索栏中的Web网页搜索
· [原创]《C#高级GDI+实战:从零开发一个流程图》第03章:画一个线,连接两个矩形!
点击右上角即可分享
微信分享提示