【问题标题】:Class composition - can't convert from 'int' to class类组合 - 无法从“int”转换为类
【发布时间】:2014-10-15 23:09:37
【问题描述】:

我正在学习类组合,但我很难理解语法是如何工作的。我有两个类,时间和日期,日期由时间对象组成。我无法让 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::Time( int hour, int minute, int second ) 
{ 
    // some validation code
}

【问题讨论】:

  • Date( int a = 1, int b = 1, int c = 1900, Time d = Time(0, 0, 0))
  • ...或Date( int = 1, int = 1, int = 1900, Time = Time());,因为您的Time 构造函数有大量默认参数。

标签: c++ constructor composition


【解决方案1】:

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

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

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

【讨论】:

  • 啊!谢谢,现在说得通了。
猜你喜欢
  • 2011-12-27
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多