练习写C++代码(10)--实现简单的时钟类2

相较前面的代码,这次增加了操作符重载,以及函数重载,并使用一个createObject方法来调用构造函数生成对象。不过没有对减法提供很好的实现。


#include 
using namespace std;

///define class Clock
class Clock
{
public:
	Clock();
	Clock(int, int);
	~Clock();
	
	///test valid
        bool test();
        bool test(int h, int m);
    
	///show the time
	void showTime();
	
	///give a prompt
	void prompt();
	
	///create object use ctor
	Clock createObject();

	///overload operator
	friend Clock operator+(const Clock& c1, const Clock& c2);
	friend Clock operator-(const Clock& c1, const Clock& c2);
	friend ostream &operator<<(ostream &os, Clock &c);

private:
	int hour;
	int minutes;	
};
///ctor
Clock::Clock()
{

}

Clock::Clock(int h, int m)
{
	hour = h;
	minutes = m;
}

Clock::~Clock()
{

}
///test valid
bool Clock::test()
{
	if (hour > 23 || hour < 0 || minutes > 59 || minutes < 0)
		return false;

	return true;
}

bool test(int h, int m)
{
	if (h > 23 || h < 0 || m > 59 || m < 0)
		return false;

	return true;
}
///show time
void Clock::showTime()
{
	cout<<"The time is:"<>h>>m;
	while (!test(h,m))
	{
		cout<<"Error input."<>h>>m;
	}
	return Clock(h,m);

}



int main()
{
	Clock clock1 = createObject();
	clock1.showTime();

	Clock clock2 = createObject();
	cout<



下次的目标是:

1.对减法进行处理

2.写一个People类来使用这个Clock

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章