【问题标题】:C++ Parent Class Default Constructor Called Instead of Parameterized Constructor调用 C++ 父类默认构造函数而不是参数化构造函数
【发布时间】:2021-08-31 16:23:30
【问题描述】:

我有一个名为“People”的父类和一个名为“Student”的子类。我已经为这两个类设置了默认和参数化构造函数,并在每个构造函数中设置了一条 cout 消息,以显示调用了哪个构造函数。但是,当我创建一个带有参数的新Student时,例如“Student newStudent(2, "Dave", true);",它调用了PARENT类的默认构造函数,但是调用了子类的参数化构造函数。所以,输出是:“People default constructor called”和“Student parameterized constructor called”。我不确定我做错了什么,因为构造函数似乎都设置正确。

int main():

Student newStudent(2, "Dave", true);

人物类(父级):

//Parent Default Constructor
People::People(){
    
    classes = 0;
    name = "";
    honors = false;

    cout << "People default constructor called" << endl;
}

//Parent Parameterized Constructor
People:People(int numClasses, string newName, bool isHonors){
    
    classes = numClasses;
    name = newName;
    honors = isHonors;

    cout << "People parameterized constructor called" << endl;
}

学生班(孩子):

//Child Default Constructor
Student::Student(){

    classes = 0;
    name = "";
    honors = false;

    cout << "Student default constructor called" << endl;
}

//Child Parameterized Constructor
Student::Student(int numClasses, string newName, bool isHonors){

    classes = numClasses;
    name = newName;
    honors = isHonors;

    cout << "Student parameterized constructor called" << endl;
}

输出:

People default constructor called
Student parameterized constructor called

【问题讨论】:

  • 需要在子构造函数的初始化列表中显式调用参数化的父构造函数。
  • 我该怎么做,代码会是什么样子?抱歉,我对编码还很陌生。
  • 在您的 C++ 书籍/教程中搜索“初始化列表”。
  • 是的......我仍然不知道该怎么办
  • 显示代码而不是代码描述的minimal reproducible example 会很有用。

标签: c++ constructor


【解决方案1】:

您需要从初始化列表中的参数化子类构造函数中调用参数化父类构造函数。比如:

class Parent
{
private:
    string str;
public:
    Parent()
    {
    }
    Parent(string s)
      : str(s)
    {
    }
};

class Child : public Parent
{
public:
    Child(string s)
      : Parent(s)
    {
    }
};

初始化列表在构造函数中很重要。我强烈建议您查找并了解它们。

【讨论】:

  • 我不断收到父类的多次初始化的编译错误
猜你喜欢
  • 2016-03-25
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
相关资源
最近更新 更多