简体   繁体   中英

initializer list: a constructor from the base class and a member function

So what I want to do is

initialize my subclass's constructor with my base class's constructor.

this is what my base class constructor looks like.

Appointment::Appointment(string description, int month, int day, int year, int hour, int minute):date(month, day, year){
    this-> hour = hour;
    this-> minute =minute;
    this-> description = description;
}

this is what my subclass constructor looks like

Daily::Daily(string description, int month, int day, int year, int hour, int minute) : Appointment(description, month, day, year, hour, minute){
}

^in my subclass's constructor (daily) there is an error that states that I need to explicitly initialize the member 'date', which does not have a default constructor.

How do I explicitly initialize both 'date' and 'Appointment' in my subclass constructor's initializer list?

Does it look something like this?

Daily::Daily(string description, int month, int day, int year, int hour, int minute) : Appointment(description, month, day, year, hour, minute):Date(month, day, year)

Thanks

Considering date and appointment , using this other question you posted, to be as:

Date date;
Appointment appointment;

You can use this constructor syntax:

Daily::Daily(string description, int month, int day, int year, int hour, int minute) : appointment(description, month, day, year, hour, minute), date(month, day, year) { ... }

Usually in a definition like:

A::A(...) : x(...), y(...), ... {...}

x(...), y(...), ... is an initializer-list which purpose is to initialize member objects of the class.

应该用逗号隔开

Daily::Daily(string description, int month, int day, int year, int hour, int minute) : Appointment(description, month, day, year, hour, minute), Date(month, day, year)

if Daily class has a (Date) and has an (Appointment) which meanse it's a composition then you have to use the initializer list as shown below

Daily::Daily(string description, int month, int day, int year, int hour, int minute) :
   Appointment(description, month, day, year, hour, minute),
   Date(month, day, year) {}

but if Daily has an (Appointment) only -composition- and as i can see the Appointment has a (Date) -composition- then the Daily constructor should be like this

Daily::Daily(string description, int month, int day, int year, int hour, int minute) :
   Appointment(description, month, day, year, hour, minute) {}

and the Appoiintment parameterized constructor will call the Date parameterized constructor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM