繁体   English   中英

C ++中的继承构造函数

[英]Inherited Constructors in C++

我正在尝试用C ++实践继承构造函数 我已经编译并在gcc中运行以下程序,它运行正常。

#include<iostream>
using namespace std;

class Base1
{
public:
        Base1()
        {
                cout<<"Base1 Default Constructor\n";
        }
        Base1(int i)
        {
                cout<<"Base1 parametrized Constructor\n";
        }
};

class Base2
{
public:
        Base2()
        {
                cout<<"Base2 Default Constructor\n";
        }
        Base2(const string& s)
        {
                cout<<"Base2 parametrized Constructor\n";
        }
};

class Derived :public Base1, public Base2
{
public:
        using Base1::Base1;
        using Base2::Base2;
};

int main()
{
        Derived d1(3);        // OK 
        Derived d2("hello");  // OK 
}

输出:

Base1 parametrized Constructor
Base2 Default Constructor
Base1 Default Constructor
Base2 parametrized Constructor

但是,我想知道, 为什么默认构造函数被调用?

正在调用默认构造函数,因为Derived继承自Base1Base2 构造Derived对象时,需要构造这两个基础。 所以,当你这样做

Derived d1(3);

你调用Base1(int i) 现在您需要构建Base2部分,因为您没有指定方式,编译器默认构造它。 同样的事情发生在

Derived d2("hello");

由于您没有指定如何在构造函数中构造Base1部件,因此编译器默认为您构造它。 然后调用Base2(const string& s)来构造Base2部分。

基本上你拥有的是什么

class Derived :public Base1, public Base2
{
public:
        Derived(int n) : Base1(n), Base2() {}
        Derived(const std::string& str) : Base1(), Base2(str) {}
};

来自cppreference http://en.cppreference.com/w/cpp/language/using_declaration
如果using-declaration引用了正在定义的类的直接基类的构造函数(例如,使用Base :: Base;),则根据以下规则继承该基类的构造函数:

1)一组候选继承构造函数由
a)基类的所有非模板构造函数(省略省略号参数后,如果有的话)(自C ++ 14起)
b)对于具有默认参数或省略号参数的每个构造函数,通过删除省略号并从参数列表的末尾逐个省略默认参数形成的所有构造函数签名
c)基类的所有构造函数模板(省略省略号参数后,如果有的话)(自C ++ 14起)
d)对于具有默认参数或省略号的每个构造函数模板,通过删除省略号并从参数列表的末尾逐个省略默认参数形成的所有构造函数签名
2)所有候选继承的构造函数都不是默认构造函数或复制/移动构造函数,并且其签名与派生类中的用户定义构造函数不匹配,在派生类中隐式声明。 默认参数不会被继承:

struct B1 {
    B1(int);
};
struct D1 : B1 {
    using B1::B1;
// The set of candidate inherited constructors is 
// 1. B1(const B1&)
// 2. B1(B1&&)
// 3. B1(int)

// D1 has the following constructors:
// 1. D1()
// 2. D1(const D1&) 
// 3. D1(D1&&)
// 4. D1(int) <- inherited
};

struct B2 {
    B2(int = 13, int = 42);
};
struct D2 : B2 {
    using B2::B2;
// The set of candidate inherited constructors is
// 1. B2(const B2&)
// 2. B2(B2&&)
// 3. B2(int = 13, int = 42)
// 4. B2(int = 13)
// 5. B2()

// D2 has the following constructors:
// 1. D2()
// 2. D2(const D2&)
// 3. D2(D2&&)
// 4. D2(int, int) <- inherited
// 5. D2(int) <- inherited
};

继承的构造函数等效于用户定义的构造函数,它们具有空主体,并且具有由单个嵌套名称说明符组成的成员初始化程序列表,该列表将所有参数转发给基类构造函数。

它具有与相应基础构造函数相同的访问权限。 如果用户定义的构造函数满足constexpr构造函数要求,那就是constexpr。 如果删除相应的基本构造函数或者删除默认的默认构造函数,则删除它(除了构造函数被继承的基础的构造不计算)。 继承构造函数无法显式实例化或显式专用。

如果两个using-declarations继承具有相同签名的构造函数(来自两个直接基类),则该程序格式错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM