类继承自没有默认构造函数的类 [英] Class inherited from class without default constructor

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

问题描述

现在我有一个类 A 继承自 B B 没有默认构造函数。我试着创建一个 A 的构造函数,它具有与 B 的构造函数完全相同的参数,但我得到:

Right now I have a class A that inherits from class B, and B does not have a default constructor. I am trying the create a constructor for A that has the exact same parameters for B's constructor, but I get:

error: no matching function for call to ‘B::B()’
note: candidates are: B::B(int)

如何修复此错误?

推荐答案

构造函数应如下所示:

A(int i) : B(i) {}

冒号后的位表示这个对象的B基类子对象使用它的 int 构造函数,值为i。

The bit after the colon means, "initialize the B base class sub object of this object using its int constructor, with the value i".

您没有为B提供初始化程序,因此默认情况下,编译器尝试使用不存在的无参数构造函数初始化它。

I guess that you didn't provide an initializer for B, and hence by default the compiler attempts to initialize it with the non-existent no-args constructor.

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

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