[英]C++ Parent Class Default Constructor Called Instead of Parameterized Constructor
I have a parent class called "People" and a child class called "Student".我有一个名为“People”的父 class 和一个名为“Student”的孩子 class。 I have set up default and parameterized constructors for both classes along with a cout message in each constructor to display which constructor was called.我已经为这两个类设置了默认和参数化构造函数,并在每个构造函数中设置了一条 cout 消息,以显示调用了哪个构造函数。 However, when I create a new Student WITH parameters, such as "Student newStudent(2, "Dave", true);", it calls the default constructor of the PARENT class, but calls the parameterized constructor of the child class.但是,当我创建一个带有参数的新Student时,例如“Student newStudent(2, "Dave", true);",它调用了PARENT class的默认构造函数,但调用了子class的参数化构造函数。 So, the output is: "People default constructor called" and "Student parameterized constructor called".因此,output 是:“调用人默认构造函数”和“调用学生参数化构造函数”。 I'm not really sure what I'm doing wrong as the constructors all seem to be set up correctly.我不确定我做错了什么,因为构造函数似乎都设置正确。
int main():诠释主要():
Student newStudent(2, "Dave", true);
People class (parent):人 class(父):
//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;
}
Student class (child):学生 class(儿童):
//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;
}
Output: Output:
People default constructor called
Student parameterized constructor called
You need to call your parameterized parent class constructor from your parameterized child class constructor in the initialization list.您需要从初始化列表中的参数化子 class 构造函数调用参数化父 class 构造函数。 Something like:就像是:
class Parent
{
private:
string str;
public:
Parent()
{
}
Parent(string s)
: str(s)
{
}
};
class Child : public Parent
{
public:
Child(string s)
: Parent(s)
{
}
};
Initialization list are important in constructors.初始化列表在构造函数中很重要。 I strongly suggest you look it up and learn about them.我强烈建议您查找并了解它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.