首页 > 解决方案 > 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;
}

标签: c++classinheritanceconstructor

解决方案


您的问题与继承无关。Student std1("Kaan", "ICYAR", "M", 23, 50, 4, 3);使用类的默认构造函数Student,它只需要 5 个参数,但您提供了 7 个。这是主要错误。在 , 的构造函数中StudentageandID是未初始化的。

... :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) {}

注意:正如您的一些评论所建议的那样,使用 , 的默认构造函数namesurnamesex不是使用“null”。你可以像下面那样做,

Employee() {
    this->name = {};
    this->surname = {};
    this->sex = {};
    this->age = 0;
    this->ID = 0;
}

推荐阅读