需要一个示例,显示默认构造函数不是继承 [英] Need an example showing that default constructor is not inherited

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

问题描述

我知道默认构造函数不是继承的,如 n3337

I know that default constructor is not inherited, as stated in n3337.

有一个例子:

struct B2 {
  B2(int = 13, int = 42);
};

struct D2 : B2 {
  using B2::B2;
};

有很好的解释:


D2 B2 的候选继承构造函数集为

The candidate set of inherited constructors in D2 for B2 is

...
—B2(int = 13, int = 42)
—B2(int = 13)
—B2()


重要:


D2 中存在的构造函数集合为

-D2(),隐式声明的默认构造函数,不是继承的

The set of constructors present in D2 is
—D2(), implicitly-declared default constructor, not inherited

对我来说,这个例子没有显示出差别,在某种意义上,即使这个非常构造函数是继承的 - 它的行为与隐式声明的默认构造函数没有不同。

For me this example does not show the difference, in a sense that even if this very constructor was inherited - its behavior was not different from the implicitly-declared default constructor.

我需要一个例子,显示一个可以容易理解的方式的差别,比如说,熟悉C ++ 03但想要学习C ++ 11的人。

I need an example showing the difference in the way that can be easily understand for, let say, an audience familiar with C++03 but wanting to learn C++11.

[UPDATE]

所有答案(包括我自己的)都是被继承,那么示例将编译/不编译

我更喜欢在结果(可观察的行为)与其他情况不同的地方。

I'd prefer answers where the outcome (observable behavior) is different than it would be otherwise.

推荐答案

请考虑:

struct foo
{
    foo() {}
    foo(int) {}
};

struct bar : foo
{
    using foo::foo;
};

int main()
{
    bar b;
}

编译: bar 没有用户声明的构造函数,默认构造函数将被隐式声明。

This compiles: Since bar has no user-declared constructors, a default constructor will be declared implicitly.

struct foo
{
    foo() {}
    foo(int) {}
};

struct bar : foo
{
    using foo::foo;
    bar(double) {}
};

int main()
{
    bar b;
}

这不编译。默认构造函数不是继承的,并且不会被隐式声明,因为有 bar(double)构造函数。

This does not compile. The default constructor is not inherited, and it is not declared implicitly, since there is the bar(double) constructor.

这篇关于需要一个示例,显示默认构造函数不是继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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