gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:23:17 25 4
gpt4 key购买 nike

我正在学习类组合,但我很难理解语法的工作原理。我有两个类,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com