[英]Class composition - can't convert from 'int' to class
我正在學習有關類組合的知識,但很難理解語法的工作原理。 我有兩個類,時間和日期,日期由一個時間對象組成。 我無法使Date構造函數正常工作-出現編譯器錯誤,指出“默認參數:無法從'int'轉換為'Time',並且我不確定如何正確設置它。我正在嘗試將默認值(0,0,0)傳遞給Time對象。
這是我的兩個班級標題。 錯誤出現在“日期”構造函數定義行上。
日期標題:
#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
}
嘗試Date( int = 1, int = 1, int = 1900, Time = Time(0, 0, 0));
語法(0,0,0)
只是一個用逗號括起來的用括號括起來的整數列表,而不是一個Time對象。
因為默認的構造函數與您提供的參數列表相同,所以您也可以執行以下操作: Date( int = 1, int = 1, int = 1900, Time = Time());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.