错误:基类构造函数必须显式初始化父类构造函数 [英] Error : base class constructor must explicitly initialize parent class constructor
本文介绍了错误:基类构造函数必须显式初始化父类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是C ++的新手。当我尝试编译下面的代码时,出现此错误
I am new to c++. When I try to compile the code below , I get this error
构造函数的'child'必须显式初始化
基类'没有默认构造函数的父级
child :: child(int a){
这是我的课程
#include<iostream>
using namespace std;
class Parent
{
public :
int x;
Parent(int a);
int getX();
};
Parent::Parent(int a)
{
x = a;
}
int Parent::getX()
{
return x;
}
class Child : public Parent
{
public:
Child(int a);
};
Child::Child(int a)
{
x = a;
}
int main(int n , char *argv[])
{
}
为什么会出现此错误?
我该如何解决?
预先感谢
Why I am getting this error ? How can I resolve it ? Thanks in advance
推荐答案
父类具有显式构造函数,因此编译器不会添加隐式空它的构造函数。另外,您的构造函数具有一个参数,因此编译器无法生成对其的隐式调用。这就是为什么您必须明确地这样做。
The parent class has an explicit constructor, so compiler will not add an implicit 'empty' constructor to it. Additionally your constructor has a parameter, so compiler can not generate an implicit call to it. That's why you must do it explicitly.
这种方式:
child::child(int a) : parent(a)
{
}
这篇关于错误:基类构造函数必须显式初始化父类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文