继承父类构造函数的c++子类
C++ Child class inheriting parent class constructor
我有一个赋值,需要从基类派生两个类。我有问题获得派生类调用基类构造函数并成功设置继承的变量。为了简单起见,我用一个虚拟程序重新创建了这个问题,因为赋值要长得多。
#include <iostream>
class ParentClass {
public:
ParentClass(int theField1, int junk);
ParentClass() {}
virtual void printField();
virtual void setField(int nf);
protected:
int field1;
};
class ChildClass : public ParentClass {
public:
ChildClass(int theField1);
void printField();
void setField(int nf);
};
ParentClass::ParentClass(int theField1, int junk) {
field1 = theField1;
}
ChildClass::ChildClass(int theField1) {
ParentClass::ParentClass(theField1, 3);
}
void ParentClass::printField() {
std::cout << "The field = " << field1 << std::endl;
}
void ChildClass::printField() {
ParentClass::printField();
std::cout << "Some other stuff." << std::endl;
}
void ParentClass::setField(int nf) {
field1 = nf;
}
void ChildClass::setField(int nf) {
ParentClass::setField(nf);
}
int main() {
ChildClass* myChild = new ChildClass(777);
ChildClass child2(888);
myChild->printField();
child2.printField();
myChild->setField(10);
myChild->printField();
child2.setField(20);
child2.printField();
return 0;
}
运行这个命令会得到以下输出:
The field = 0
Some other stuff.
The field = 4197296
Some other stuff.
The field = 10
Some other stuff.
The field = 20
Some other stuff.
为什么前两次尝试都不成功?调用构造函数应该将变量初始化为作为参数传递的值,但是直到我特别调用mutator函数才真正设置它们。我尝试了第三个类,它在构造函数中使用父变量函数,而不是父构造函数:
class StepChild : public ParentClass {
public:
StepChild(int nf);
};
StepChild::StepChild(int nf) {
ParentClass::setField(nf);
}
main中定义的对象:
StepChild* step = new StepChild(30);
step->printField();
输出:The field = 30
我在哪里出错,试图使用父构造函数没有正确初始化这些变量?
我也试着改变父类不是虚拟的,它工作得很好,所以它似乎不是父类的问题。
使用初始化列表:
ParentClass::ParentClass(int theField1, int junk)
: field1(theField1)
{ }
ChildClass::ChildClass(int theField1)
: ParentClass(theField1, 3)
{ }
下面的代码——来自你的代码——创建一个临时的ParentClass对象并将其丢弃——它对正在构造的ChildClass对象没有影响:
ParentClass::ParentClass(theField1, 3); // temporary
如果要使参数匹配,也可以用c++11的方式将
using ParentClass::ParentClass( int, int );
在你的ChildClass类定义中。它与从ChildClass构造函数初始化器列表中调用父构造函数相同,但没有那么深奥。
不确定,但我发现你调用基类构造函数的方式有问题。
尝试用这种方法调用基类构造函数,看看问题是否解决了。
相关文章:
- 继承期间显示未知行为的子类
- 通过指向指针数组的指针访问子类的属性
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- 避免在C++中重复子类定义
- 将QOpenGLWidget子类转换为使用Metal而不是OpenGL的子类是否可行?
- 如何初始化矢量的模板化子类
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 使用子类覆盖基类中定义的函数
- 子类地址等于虚拟基类地址?
- 将子类方法声明为基类的友元
- C++子类共享变量?
- 如何检查模板专用化是否是基本模板的子类?
- 仅让特定类'Fabric'构造类'Foo'及其所有子类的实例
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 如何在C++子类中访问父类的私有变量
- 将父类的子类的数据复制到具有相同父类的另一个类