【发布时间】: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