#c++程序语言设计戴波-
第八章:课上实验
2.行走的时钟类
代码一:
main.cpp
#include<iostream>
#include<Windows.h>
#include"clock.h"
using namespace std;
//使用类
int main()
{
Clock c;
while (1) {
system("cls");//每次清空showtime。
c.addonesecond();
c.showtime();
Sleep(1000);
}
}
代码二:clock.cpp
#include "clock.h"
#include<iostream>
using namespace std;
//实现类
Clock::Clock()
{
h = m = s = 0;
}
Clock::~Clock()
{
}
Clock::Clock(int h, int m, int s)
{
this->h = h;
this->m = m;
this->s = s;
}
Clock::Clock(Clock & c)
{
h = c.h;
m = c.m;
s = c.s;
}
void Clock::settime(int h, int m, int s)
{
this->h = h;
this->m = m;
this->s = s;
}
void Clock::showtime()
{
cout << h << ":" << m << ":" << s << endl;
}
void Clock::gettime(int &h, int& m, int& s)
{
h = this->h;
m = this->m;
s = this->s;
}
void Clock::addonesecond()
{
s++;
if(s>=60)
{
m++;
s = 0;
if (m >= 60)
{
m = 0;
h++;
if (h >= 12)
{
h = 0;
}
}
}
}
代码三:类的构建
#pragma once
//声明类
class Clock
{
public:
//构造函数
int h, m, s;
Clock();
Clock(int h, int m, int s);
Clock(Clock &a);
~Clock();//析构函数
void settime(int h, int m, int s);
void showtime();
void gettime(int& h, int& m, int& s);
void addonesecond();
};