无法让派生类使用其基类的构造函数
Can't get a derived class to use its base class's constructor
所以我有一个名为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 */ }
};
相关文章:
- C++17 使用驱动类常量作为基类构造函数的参数来初始化基类构造函数
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 在成员构造函数之后调用基类构造函数
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- C++:在共享对象中调用抽象基类构造函数/未定义的符号
- 如何在 C++ 中将参数传递给基类构造函数
- 将数据成员的指针传递给基类构造函数是否安全?
- 使用基类构造函数初始化儿童类
- 使用基类构造函数的子类构造函数的大纲定义
- MSVC 无法识别继承模板类的模板类的"直接"基类构造函数
- 子类的构造函数后跟冒号后的基类构造函数是什么意思?
- 是否可以使用基类构造函数通过派生类将值初始化为基类私有成员?
- 当派生类无法轻易将参数传递到基类时,如何调用基类构造函数
- 是否可以在运行时切换到不同的基类构造函数?
- 对基类构造函数的未定义引用
- 如何为基类构造函数中的每个子类执行特定任务
- 将类传递到基类构造函数的模板参数中?
- 如何在基类构造函数中使用派生类成员
- (为什么)纯虚拟派生类中是否需要虚拟基类构造函数调用?
- 使用相同的参数调用基类C++构造函数