c++ - C++中一个对象的继承和构造
问题描述
我正在研究 C++ 中的继承。我试图在一个对象“std1”中获取所有信息(没有更多功能。我设法用其他功能来做到这一点)。我使用构造方法,但它不断给出错误。你能帮助我吗?
#include <iostream>
using namespace std;
class Employee {
protected:
string name;
string surname;
string sex;
int age;
int ID;
public:
Employee(){
this->name = "null";
this->surname = "null";
this->sex = "null";
this->age = 0;
this->ID = 0;
}
Employee(string name, string surname, string sex, int age, int ID):name(name), surname(surname), sex(sex), age(age), ID(ID){}
void changeInformations(string name, string surname, string sex, int age, int ID) {
this->name = name;
this->surname = surname;
this->sex = sex;
this->age = age;
this->ID = ID;
}
};
class Student :public Employee {
public:
int year;
double GPA;
Student(string name, string surname, string sex, int year , int GPA):Employee(name, surname, sex, age, ID),year(year), GPA(GPA){}
void printStudent() {
cout << "Name : " << name << endl << "Surname : " << surname << endl << "Sex : " << sex << endl << "Age : " << age << endl << "ID : " << ID << endl << "Year : " << year << endl << "GPA :" << GPA << endl;
}
};
int main()
{
Student std1("Kaan", "ICYAR", "M", 23, 50, 4, 3);
std1.printStudent();
return 0;
}
解决方案
您的问题与继承无关。Student std1("Kaan", "ICYAR", "M", 23, 50, 4, 3);
使用类的默认构造函数Student
,它只需要 5 个参数,但您提供了 7 个。这是主要错误。在 , 的构造函数中Student
,age
andID
是未初始化的。
... :Employee(name, surname, sex, age, ID), year(year), GPA(GPA) {}
^ ^
这意味着您最终会得到两个未初始化的变量。
我认为您要寻找的答案是添加int age, int ID
到构造函数的参数中。
Student(string name, string surname, string sex, int year, int GPA, int age, int ID) :Employee(name, surname, sex, age, ID), year(year), GPA(GPA) {}
注意:正如您的一些评论所建议的那样,使用 , 的默认构造函数name
,surname
而sex
不是使用“null”。你可以像下面那样做,
Employee() {
this->name = {};
this->surname = {};
this->sex = {};
this->age = 0;
this->ID = 0;
}
推荐阅读
- css - 如何在 React 中隐藏包装的组件
- cassandra - 无法强制转换为格式化日期 - Cassandra 时间戳类型
- laravel - laravel 数据库种子数据透视表
- java - 处理3中二维数组的变化值
- ios - 在 UIViewControllerTransitioning 如何在转换进行时点击视图内的按钮?
- javascript - 从索引视图中的部分视图重新渲染索引视图?
- java - 如何通过 Android HAL 创建环回摄像头?
- javascript - Javascript绑定函数实现
- android - 使用 MDC 在 android 中创建材质微调器下拉列表
- javascript - 使用 React.JS 将图像文件与其他数据一起发送到 Java 后端