練習寫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

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