使用另一个类的对象的类构造函数
Posted
技术标签:
【中文标题】使用另一个类的对象的类构造函数【英文标题】:Class constructor using object of another class 【发布时间】:2020-04-30 15:07:19 【问题描述】:在这段代码中,我想使用生日类的对象,日期类的构造函数是:
Date(unsigned int y, unsigned int m, unsigned int d);
Date(string yearMonthDay); // yearMonthDay must be in format "yyyy/mm/dd"
但我收到一个错误:“类 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
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;
;
【问题讨论】:
【参考方案1】:使用构造函数初始化列表:
Person::Person(std::string name, char gender, Date birthday)
: name(name), gender(gender), birthday(birthday)
// Empty
这将初始化成员仅使用参数一次,调用成员的适当构造函数。
如果没有构造函数初始化列表,成员将被默认初始化(默认构造),然后在构造函数的主体中使用正常的成员赋值。
【讨论】:
【参考方案2】:当您编写任何自己的构造函数时,编译器不再提供无参数构造函数。您可以恢复它(要求提供):
Date() = default;
为确保您可以安全地默认构造 Date
,您应该为其成员提供适当的默认值:
private:
unsigned int year2000;
unsigned int month4;
unsigned int day30;
【讨论】:
但前提是这样做是有意义的。它可能不会。 没错,我只是在这种情况下修复了症状。但我不知道答案本身是否错误,所以我就不说了。 @AsteroidsWithWings 您会惊讶地发现需要默认 ctor 的频率,例如分配日期或人员数组。 @franji1 您会惊讶地发现,不需要的默认ctor的频率。你为什么用new[]
?
日期就是日期。这不应该是一个不约会。以上是关于使用另一个类的对象的类构造函数的主要内容,如果未能解决你的问题,请参考以下文章