类组成 - 无法从"int"转换为类

Class composition - can't convert from 'int' to class

本文关键字:int 转换      更新时间:2023-10-16

我正在学习类组成,但很难理解语法是如何工作的。我有两个类,Time和Date,Date是由一个Time对象组成的。我无法使Date构造函数正常工作-有一个编译器错误,说明"默认参数:无法从'int'转换为'Time',我不知道如何正确设置。我正在尝试将默认值(0,0,0)传递给Time对象。

这是我的两个班头。错误出现在Date构造函数定义行上。

日期标题:

#ifndef DATE_H
#define DATE_H
#include "Time.h"
class Date 
{
public:
   static const unsigned int monthsPerYear = 12; // months in a year
   Date( int = 1, int = 1, int = 1900, Time = (0, 0, 0)); // <- ERROR with this line
   ~Date(); // provided to confirm destruction order
   void print() const; // print date in month/day/year format
   void tick();      // function that increments seconds by 1.
   void increaseADay(); // increases the day by one
private:
   unsigned int month; // 1-12 (January-December)
   unsigned int day; // 1-31 based on month
   unsigned int year; // any year
   Time time;  // private Time object - class composition
   // utility function to check if day is proper for month and year
   unsigned int checkDay( int ); 
}; // end class Date
#endif

时间头:

#ifndef TIME_H
#define TIME_H
// Time class definition
class Time 
{
public:
   explicit Time( int = 0, int = 0, int = 0 ); // default constructor
   ~Time();  // destructor
   // set functions
   void setTime( int, int, int ); // set hour, minute, second
   void setHour( int ); // set hour (after validation)
   void setMinute( int ); // set minute (after validation)
   void setSecond( int ); // set second (after validation)
   // get functions
   unsigned int getHour() const; // return hour
   unsigned int getMinute() const; // return minute
   unsigned int getSecond() const; // return second
   void printUniversal() const; // output time in universal-time format
   void printStandard() const; // output time in standard-time format
private:
   unsigned int hour; // 0 - 23 (24-hour clock format)
   unsigned int minute; // 0 - 59
   unsigned int second; // 0 - 59
}; // end class Time
#endif

在我的Date实现文件中,这是我不确定如何处理Time构造函数的地方,这很可能是我的错误所在

Date::Date( int mn, int dy, int yr, Time time)
{
    // some validation code
}

我的时间构造函数是这样的:

Time::Time( int hour, int minute, int second ) 
{ 
    // some validation code
}

尝试Date( int = 1, int = 1, int = 1900, Time = Time(0, 0, 0));

语法(0,0,0)只是一个逗号分隔的用括号括起来的int列表,而不是Time对象。

因为默认构造函数与您提供的参数列表相同,所以您也可以这样做Date( int = 1, int = 1, int = 1900, Time = Time());