继承和重载默认构造函数 [英] Inherit and overload default constructor

查看:115
本文介绍了继承和重载默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找这个,我很惊讶,我没有找到任何东西。为什么不能使用使用声明继承基类构造函数并在派生类中添加重载?我使用Visual C ++ 2013,当默认构造 b 时,基类构造函数被忽略:

I've been searching for this and I'm amazed I haven't found anything. Why can't I inherit a base class constructor using using declaration and add an overload in the derived class? I'm using Visual C++ 2013, the base class constructor is ignored when default-constructing b:

error C2512: 'B' : no appropriate default constructor available



< ve通过重新定义构造函数来处理这个问题,但是我不喜欢这样。这只是一个最小的例子,如果我只有一个基类构造函数,它不会打扰我。

I've dealt with this by re-defining the constructors, but I don't like that. This is just a minimal example, it wouldn't bother me if I had only one base class constructor.

struct A
{
    A() : a(10) {}

    int a;
};

struct B : A
{
    using A::A;

    explicit B(int a) { this->a = a; }
};

int main()
{
    B b;
}


推荐答案

构造函数不被继承。从[class.inhctor] / p3:

The problem is that default-constructors are not inherited. From [class.inhctor]/p3:


对于候选的继承构造函数[..]中的每个非模板构造函数,构造函数隐式声明为具有相同的构造函数特性,除非有一个用户声明的构造函数,在完成类中使用相同的签名,其中使用声明出现或构造函数将是默认的副本,或移动该类的构造函数。

For each non-template constructor in the candidate set of inherited constructors [..], a constructor is implicitly declared with the same constructor characteristics unless there is a user-declared constructor with the same signature in the complete class where the using-declaration appears or the constructor would be a default, copy, or move constructor for that class.

您还有一个用户声明的构造函数,默认构造函数。只需添加默认值即可使其有效:

You also have a user-declared constructor that suppresses the creation of an implicit default-constructor. Just add a defaulted one to make it work:

B() = default;

这篇关于继承和重载默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆