为什么我不能通过构造函数更新派生类的默认值?

问题描述 投票:0回答:1

我正在努力思考继承问题。

我创建了一个 BasePerson 类,它具有一些受保护的元素,并且这些元素具有默认值。我试图用其他值“更新”派生类中的这些默认值,并从 main.cpp 文件中的类外部调用它们。

如果我正确理解了继承,我应该能够从主文件调用派生类并显示“更新的”元素,但我在某个地方犯了错误,因为只显示了基类的默认值。

我已经获得了代码,如果我愿意,我可以更新 main.cpp 文件中的值,但这不是我想要做的。

#include <iostream>
#include <string>
#include "BasePerson.h"
using namespace std;

#include <string>
#include <iostream>
using namespace std;

class BasePerson
{
protected :
    string st_firstName;
    string st_lastName;

public :
    double d_wagePerHour;

    BasePerson()
    {
        st_firstName = "Default First Name";
        st_lastName = "Default Last Name";
        d_wagePerHour = 40.12;
    }

    BasePerson(string param_firstName, string param_lastName, double param_wage)
    {
        st_firstName = param_firstName;
        st_lastName = param_lastName;
        d_wagePerHour = param_wage;
    }


    //Print-all Function
    void fn_printAllInfo()
    {
        cout << "First Name: " << st_firstName << "\n" << "Last Name: " << st_lastName << "\n" << "Wage Per Hour: " << d_wagePerHour << endl;
    }

};


class Employee : public BasePerson
{

private :
    string st_career;


public :
    Employee()
    {
       st_career = "Default Career";
    }

    Employee(string param_firstName, string param_lastName, double param_wage, string param_career) : BasePerson(param_firstName, param_lastName, param_wage)
    {
        st_firstName = "Bob";
        st_lastName = "Vila";
    }


};



/*
    Notes:

        - Anything private will be inaccessible from the derived class and outside
        - Anything protected will be accessible from the derived class and inaccessible from the outside
        - Public is public.
*/



int main()
{

    BasePerson person1;
    person1.fn_printAllInfo();

    Employee emp1;
    emp1.fn_printAllInfo();


    return 0;
}

c++ inheritance protected
1个回答
0
投票

您当前尚未在 Employee 默认构造函数中设置值。如果您希望默认构造函数设置所有三个值,请尝试以下操作:

Employee()
{
    st_career = "Default Career";
    st_firstName = "Bob";
    st_lastName = "Vila";
    
}

Employee(string param_firstName, string param_lastName, double param_wage, string param_career) 
: BasePerson(param_firstName, param_lastName, param_wage)
{
    st_career = param_career;
}

您还应该考虑初始化成员初始值设定项列表中的所有成员变量:

Employee() : BasePerson("Bob", "Vila", 40.12), st_career("Default Career") {}
© www.soinside.com 2019 - 2024. All rights reserved.