继承父类构造函数的c++子类

C++ Child class inheriting parent class constructor

本文关键字:c++ 子类 构造函数 父类 继承      更新时间:2023-10-16

我有一个赋值,需要从基类派生两个类。我有问题获得派生类调用基类构造函数并成功设置继承的变量。为了简单起见,我用一个虚拟程序重新创建了这个问题,因为赋值要长得多。

#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构造函数初始化器列表中调用父构造函数相同,但没有那么深奥。

不确定,但我发现你调用基类构造函数的方式有问题。

尝试用这种方法调用基类构造函数,看看问题是否解决了。