具有其他类数据类型的C++构造函数

C++ Constructor with other class-data-type

本文关键字:C++ 构造函数 数据类型 其他      更新时间:2023-10-16

首先,大家好,

我是这个论坛的新手,所以我希望,我没有犯任何新手错误,如果是的话,请纠正我:)。第二:英语不是我的母语,所以我希望我能把我的问题说清楚。

关于我的问题:

我必须写一个有两个类的C++程序,类1 Date用3x unsigned int表示天、月和年,类2 Time用2x unsignedint表示分钟和小时,以及1x Date。

  • 每个类都有一个默认构造函数,它调用重载构造函数(我们必须使用initializer列表)我的问题是,我只是不明白,我如何才能在我的时间类中使用Date类的成员

我知道我的问题是什么还不完全清楚,所以下面是我代码的简化版本:main:

#include "Date.hpp"
#include "Time.hpp" //(+ iomanip / iostream)
int main(){
Date d1; //Calls Default Constructor of class Date, which initialises with (1,1,2000)
Time t1(d1,23,30); //should call ovrld-constr. of class Time and keep the date of d1

在我的"Time.cpp"中,我尝试了类似的smth

Time::Time(Date x, unsigned int y, unsigned int z)
  : d(Date::Date(x)), minute(y), hour(z) //try to call the def constr of class Date
{
return;
} 
Time::Time() : Time(Date::Date(), 00, 00) //should call the ovrld constr of class Time
{
return;
}

但它当然不起作用。。。编译器总是说:

main.cpp:(.text+0x35c):undefined reference to `Time::Time()'

如果有帮助的话,下面是我的(完全工作的)"Date.cpp"的摘录:

Date::Date(unsigned int x, unsigned int y, unsigned int z)
 : day(x), month(y), year(z)
{
if(valiDate(day, month, year)==false){ //ValiDate is a function which checks the input                          
day=1;month=1;year=2000;} //default date, if Date is not Valid
return;
} 
Date::Date() : Date(1,1,2000)
{
return;
}

我希望这足以让我的问题清楚,如果没有,我可以随时向你展示完整的源代码。重要提示:我不允许(!)编辑main.cpp。此外,如果有人能解释我的错误,而不仅仅是发布一个完整的解决方案,我将不胜感激,因为我认为,在最坏的情况下,我甚至不理解的解决方案对我的学习没有多大帮助。

提前感谢您的帮助,

致以最良好的问候。

编辑:

对不起,我忘了上两节课

1) 工作日期.hpp(摘录)

class Date
{
public:
  Date();
  Date(unsigned int, unsigned int, unsigned int);

private:
  unsigned int day, month, year; 
  bool valiDate(unsigned int, unsigned int, unsigned int);
};

2) 我(不工作)的时间

class Time
{
  public:
  Time();
  Time(Date, unsigned int, unsigned int);
  private:
  unsigned int minute, hour;
  Date d;
};

我复制了您的项目,发现了几十个编译和链接错误,但没有您指定的错误。以下是我的发现:

class Time按值包含Date类型的数据成员,因此您需要在Time.hpp中使用#include Date.hpp。如果您还没有这样做,则需要在标头中添加include guard。

您不需要在Time的成员初始值设定项中显式指定Date构造函数,因为它无论如何都会被调用:

Time::Time(Date x, unsigned int y, unsigned int z)
  : d(Date::Date(x)), minute(y), hour(z) //try to call the def constr of class Date
{
    return;
} 

可以是:

Time::Time(Date x, unsigned int y, unsigned int z)
    : d(x), minute(y), hour(z)
{
} 

请注意,您也不需要在构造函数中编写return语句。还要注意,: d(x)调用Date的复制构造函数,而不是默认构造函数。您还没有定义复制构造函数,因此正在隐式创建一个副本构造函数,以便进行浅层复制。

您还从另一个构造函数调用一个构造函数:

Time::Time() : Time(Date::Date(), 00, 00)
Date::Date() : Date(1,1,2000)

C++11中支持委派构造函数,但还不是所有编译器都支持,但您可以自己初始化成员:

Time::Time() : minute(0),hour(0)
Date::Date() : day(1),month(1),year(2000)