无法让派生类使用其基类的构造函数

Can't get a derived class to use its base class's constructor

本文关键字:基类 构造函数 派生      更新时间:2023-10-16

所以我有一个名为package的类,它有一堆变量。我有所有的获取/设置方法和一个构造函数在工作。

包头代码

三天标题代码

两天标题代码

包类代码

三日班代码

两天课程代码

我有两个派生类,名为 twoDay 和 threeDay,它们继承了包类,需要使用其构造函数。

包类的构造函数:

package::package(string sN, string sA, string sC, string sS, int sZ, string rN, string rA, string rC, string rS, int rZ, int w, int c) {
    this->senderName = sN;
    this->senderAddress = sA;
    this->senderCity = sC;
    this->senderState = sS;
    this->senderZip = sZ;
    this->receiverName = rN;
    this->receiverAddress = rA;
    this->receiverCity = rC;
    this->receiverState = rS;
    this->receiverZip = rZ;
    this->weight = w;
    this->cpo = c;

}

我一直在 threeDay 标头中的构造函数中使用这段代码:

threeDay(string, string, string, string, int, string, string, string, string, int,int,int);

我需要发生的是有两天和三天才能使用构造函数。 我的意思是派生包需要能够使用基类构造函数。

我目前收到此错误:

threeDay.cpp:10:136: error: no matching function for call to ‘package::package()’

我从这个链接做了一些研究:http://www.cs.bu.edu/teaching/cpp/inheritance/intro/

和这个链接: C++ 构造函数/析构函数继承

所以看起来我没有直接继承构造函数,我仍然需要定义它。如果是这样的话,为什么我的代码现在不起作用?

但我似乎无法让它工作。

一旦我让构造函数工作,它就会一帆风顺。

由于package没有默认构造函数(即不带参数的构造函数),因此您需要告诉派生类如何构建package

执行此操作的方法是在派生类的初始化器列表中调用基类构造函数,如下所示:

struct Base
{
    Base(int a);
};
struct Derived : public Base
{
    Derived(int a, string b) : Base(a) { /* do something with b */ }
};