C++试题:声明和实现一个时间类time24:a)实现获得和设置由时,分组成的24小时制时间的方法(具体看补充)
用C++声明和实现一个时间类time24:a)实现获得和设置由时,分组成的24小时制时间的方法;b)编写程序实现“+”运算,即实现time24对象与整型分钟数相加的运算,...
用C++声明和实现一个时间类time24:
a)实现获得和设置由时,分组成的24小时制时间的方法;
b)编写程序实现“+”运算,即实现time24对象与整型分钟数相加的运算,要求该运算返回一个time24对象;
c)实现time24类的等价运算符重载,即比较两个time24对象是否相等;
d)实现输入和输出重载。
要求该类具有构造函数,并适当使用友元函数和运算符重载方法。 展开
a)实现获得和设置由时,分组成的24小时制时间的方法;
b)编写程序实现“+”运算,即实现time24对象与整型分钟数相加的运算,要求该运算返回一个time24对象;
c)实现time24类的等价运算符重载,即比较两个time24对象是否相等;
d)实现输入和输出重载。
要求该类具有构造函数,并适当使用友元函数和运算符重载方法。 展开
1个回答
展开全部
#include <exception>
#include <ostream>
class invalid_time : std::exception {};
class time24
{
public:
time24(unsigned hour, unsigned min);
~time24();
void set(unsigned hour, unsigned min);
void add_min(unsigned min);
unsigned hour() const;
unsigned min() const;
private:
unsigned _hour;
unsigned _min;
friend bool operator==(time24 const&, time24 const&);
};
time24::time24(unsigned hour, unsigned min)
: _hour(0), _min(0)
{
set(hour, min);
}
time24::~time24()
{
}
void time24::set(unsigned hour, unsigned min)
{
if( hour>23 || min>59 )
throw invalid_time();
_hour = hour;
_min = min;
}
void time24::add_min(unsigned min)
{
unsigned dh = (_min + min) / 60;
_hour = (_hour + dh) % 24;
_min = (_min + min) % 60;
}
unsigned time24::hour() const
{
return _hour;
}
unsigned time24::min() const
{
return _min;
}
time24& operator+(time24& t, unsigned min)
{
t.add_min(min);
return t;
}
time24& operator+(unsigned min, time24& t)
{
return operator+(t, min);
}
bool operator==(time24 const& lhs, time24 const& rhs)
{
return lhs._hour == rhs._hour
&& lhs._min == rhs._min;
}
std::ostream& operator<<(std::ostream& os, time24 const& t)
{
os << "hour=" << t.hour() << ", min=" << t.min();
return os;
}
唉,这5分赚得累呀
#include <ostream>
class invalid_time : std::exception {};
class time24
{
public:
time24(unsigned hour, unsigned min);
~time24();
void set(unsigned hour, unsigned min);
void add_min(unsigned min);
unsigned hour() const;
unsigned min() const;
private:
unsigned _hour;
unsigned _min;
friend bool operator==(time24 const&, time24 const&);
};
time24::time24(unsigned hour, unsigned min)
: _hour(0), _min(0)
{
set(hour, min);
}
time24::~time24()
{
}
void time24::set(unsigned hour, unsigned min)
{
if( hour>23 || min>59 )
throw invalid_time();
_hour = hour;
_min = min;
}
void time24::add_min(unsigned min)
{
unsigned dh = (_min + min) / 60;
_hour = (_hour + dh) % 24;
_min = (_min + min) % 60;
}
unsigned time24::hour() const
{
return _hour;
}
unsigned time24::min() const
{
return _min;
}
time24& operator+(time24& t, unsigned min)
{
t.add_min(min);
return t;
}
time24& operator+(unsigned min, time24& t)
{
return operator+(t, min);
}
bool operator==(time24 const& lhs, time24 const& rhs)
{
return lhs._hour == rhs._hour
&& lhs._min == rhs._min;
}
std::ostream& operator<<(std::ostream& os, time24 const& t)
{
os << "hour=" << t.hour() << ", min=" << t.min();
return os;
}
唉,这5分赚得累呀
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询