【问题标题】:Inheritence and construction in one object in C++C++中一个对象的继承和构造
【发布时间】: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-&gt;name = "null"; 可能不应该存在。 std::string 的默认构造函数将字符串初始化为空字符串。
  • "我使用构造方法,但它经常出错。" - 究竟是什么错误?将完整的错误复制粘贴到问题中。
  • 这里您尝试使用构造函数的 7 个参数构造 StudentStudent std1("Kaan", "ICYAR", "M", 23, 50, 4, 3);Student 没有使用 7 个参数的构造函数。
  • int age, int ID 缺少学生构造函数
  • 呃,真是个错误。当我添加“int age,int ID”时,它正在工作。感谢您的帮助。

标签: c++ class inheritance constructor


【解决方案1】:

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

... :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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-29
    • 2014-12-27
    • 2018-06-28
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多