【发布时间】:2021-02-15 17:33:22
【问题描述】:
我正在研究 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;
}
【问题讨论】:
-
this->name = "null";可能不应该存在。 std::string 的默认构造函数将字符串初始化为空字符串。 -
"我使用构造方法,但它经常出错。" - 究竟是什么错误?将完整的错误复制粘贴到问题中。
-
这里您尝试使用构造函数的 7 个参数构造
Student:Student std1("Kaan", "ICYAR", "M", 23, 50, 4, 3);但Student没有使用 7 个参数的构造函数。 -
int age, int ID缺少学生构造函数 -
呃,真是个错误。当我添加“int age,int ID”时,它正在工作。感谢您的帮助。
标签: c++ class inheritance constructor