为什么不继承C ++构造函数? [英] Why aren't C++ constructors inherited?

查看:147
本文介绍了为什么不继承C ++构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在此代码中需要通过子代构造函数?我以为不会,但是当我删除它时,编译器(gcc和VS2010)抱怨。有一个优雅的解决方法吗?似乎没有必要将此垫片插入子类。

Why is the Child pass-through constructor necessary in this code? I would think that it wouldn't be, but the compiler (gcc and VS2010) complains when I remove it. Is there an elegant workaround? It just seems pointless to have to insert this shim into child classes.

class Parent
{
public:
  Parent(int i) { }
};

class Child : public Parent
{
public:
  Child(int i) : Parent(i) { }
};

int main()
{
  Child child(4);
  return 0;
}


推荐答案

因为以下内容完全有效:

Because the following is perfectly valid:

class Parent
{
public:
    Parent(int i) { }
};

class Child : public Parent
{
public:
    Child() : Parent(42) { }
};

编译器如何猜测您是否希望派生子对象具有转发的构造函数?在多重继承的情况下,两种类型的构造函数的集合可能不匹配;从基类A转发一个构造函数时,应该调用基类B上的哪个构造函数?

How is the compiler to guess whether you want the derived child to have a forwarded constructor? And in the case of multiple inheritance, the set of constructors from the two types may not match; when forwarding a constructor from base class A, which constructor on base class B should be called?

从技术上讲,我想语言设计者可能会说,如果类型具有单个基类,并且在没有显式构造函数的情况下,将转发所有父构造函数。但是,这会产生相反的问题:如果基类具有多个构造函数(包括默认构造函数),并且子级希望仅允许使用默认构造函数,则现在必须明确指定它。

Technically, I suppose the language designers could have said that if the type has a single base class and in the absence of an explicit constructor, all parent constructors are forwarded. However, that creates the opposite problem: if a base class has multiple constructors including a default constructor, and the child wishes to allow only the default constructor, this must now be explicitly specified.

这篇关于为什么不继承C ++构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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