简体   繁体   中英

Class constructor using object of another class

In this code, I would like to use an object of class birthday, the constructors of class Date are:

    Date(unsigned int y, unsigned int m, unsigned int d);
    Date(string yearMonthDay); // yearMonthDay must be in format "yyyy/mm/dd"

But I'm getting an error: "No default constructor exist for class Date"

class Person {

public:
    Person(std::string name, char gender, Date birthday);
    string getName();
    char getGender();
    int getYear();
    int getMonth();
    int getDay();

private:
    Date birthday;
    std::string name;
    char gender;
};

Person::Person(std::string name, char gender, Date birthday){
    Person::name = name;
    Person::gender = gender;
    Person::birthday = birthday;
}

Class Date:

class Date {
public:
    Date(unsigned int y, unsigned int m, unsigned int d);
    Date(string yearMonthDay); // yearMonthDay must be in format "yyyy/mm/dd"
    void setYear(unsigned int y);
    void setMonth(unsigned int m);
    void setDay(unsigned int d);
    void setDate(unsigned int y, unsigned int m, unsigned int d);
    unsigned int getYear() const;
    unsigned int getMonth() const;
    unsigned int getDay() const;
    string getDate() const; // returns the date in format "yyyy/mm/dd"

private:
    unsigned int year;
    unsigned int month;
    unsigned int day;
};

Use a constructor initializer list :

Person::Person(std::string name, char gender, Date birthday){
    : name(name), gender(gender), birthday(birthday)
{
    // Empty
}

That will initialize the members only once using the arguments, calling the appropriate constructors of the members.

Without a constructor initializer list, the members will be default initialized (default constructed) and then in the body of the constructor you use normal assignment to the members.

When you write any of your own constructors, the no-argument constructor is no longer supplied by the compiler. You can reinstate it (ask for it to be supplied) though:

Date() = default;

To make sure that you can default construct a Date safely, you should give proper defaults to its members:

private:
    unsigned int year{2000};
    unsigned int month{4};
    unsigned int day{30};

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