【问题标题】:Child Class constructor using private member使用私有成员的子类构造函数
【发布时间】:2016-08-28 01:11:24
【问题描述】:

我有多个扩展基类(媒体)的子类。 当我调用子类构造函数时,我无法使用私有成员 mBookLateFee 的值进行一些计算。它似乎使用的是默认值 0.0 而不是成员内容。 但是,如果我将 1.25 的实际值放在那里,它就可以工作..

对象在构造时不能从子类成员初始化吗?

class Media {

private :
    string mCallNumber;

protected:
    string mStatus;
    string mTitle;
    string mType;
    int mDaysOverDue = 0;
    double mDailyLateFee = 0.0;
    double mTotalLateFees = 0.0;

public:
    Media(string status, string title, int days=0, string callNum="", string type="", double fee=0.0) : mStatus(status),
            mTitle(title), mDaysOverDue(days), mCallNumber(callNum), mType(type), mDailyLateFee(fee) {};
    ~Media(){};
    void setCallNo(string newCallNum);
    string getCallNo();
    void setHowLate(int numDays);
    int getDaysOverDue();
    virtual void print();
    virtual double getFees() = 0;

};




class Book : public Media {
private:
    double mBookLateFee = 1.25;

protected:
    string mAuthor;
    int mNumPages;

public:
    Book(string status, string title, int days, string callNum, string author, int pages=0) :
                Media(status, title, days, callNum, "Book", mBookLateFee), mAuthor(author), mNumPages(pages){
                    mTotalLateFees = mDaysOverDue * mDailyLateFee;
                };
    double getFees() { return mTotalLateFees;}
    void print();

};

【问题讨论】:

    标签: c++ inheritance constructor


    【解决方案1】:

    超类,即父类,在子类之前构造。

    当你的子类调用父类的超类的构造函数时,子类还没有被构造。它的mBooklateFee 尚未构建。

    从某种意义上说,它还不存在。因此,您不能使用它来调用父类的构造函数。

    【讨论】:

    • 我以为是这样,谢谢您的确认!
    猜你喜欢
    • 1970-01-01
    • 2016-07-31
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2020-11-08
    • 2017-04-04
    • 2015-03-21
    相关资源
    最近更新 更多