c++ - 类组合 - 无法从 'int' 转换为类

标签 c++ constructor composition

我正在学习类组合,但我很难理解语法的工作原理。我有两个类,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::Date( int mn, int dy, int yr, Time time)
{
    // some validation code
}

我的时间构造函数如下所示:

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

最佳答案

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

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

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

关于c++ - 类组合 - 无法从 'int' 转换为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26393619/

相关文章:

c++ - 为什么要为 std::forward_list 拼接整个列表或线性范围?

c++ - 如何在 C++ 中消除 vector 的 "doubled"元素

c++ - 关于 C++ 中的 throw()

c++ - 私有(private)继承的组合

haskell - 什么时候变质的组合是变质?

c++ - 使用 boost::any 时出现错误 C2451

c# - 定义构造函数签名的接口(interface)?

javascript - 为什么代码放在return语句后面,它会被执行吗?

c++:需要正确的语法以避免 MISRA 14-6-1 警告。具有依赖基类的类模板

c++ - 组合:使用特征来避免转发功能?