#include"Clock.h" #include<iostream> using namespace std; int main() { int h, m, s; cin >> h >> m >> s; Clock c1(h, m, s), c2(c1); c1.SetTime(10, 20, 30); c1.getTime(h, m, s); cout << "c1:" << h << ":" << m << ":" << s << endl; c2.ShowTime(); system("pause"); return 0; }
#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::getTime(int& h, int& m, int& s) { h = this->h; m = this->m; s = this->s; } void Clock::ShowTime() { cout << h << ":" << m << ":" << s << endl; }
#pragma once class Clock { public: Clock(int h, int m,int s); Clock(); Clock(Clock &c); ~Clock() ; int h, m, s; void SetTime(int h, int m, int s); void getTime(int& h, int& m, int& s); void ShowTime(); };
以上是出自慕课程序设计基础(C&C++)中第八章编程实战的内容
以上是简单时钟板块,这里要注意按原慕课中代码在Visual Stdio 上生成会出错,原因是重复声明了h,m,s要在private中删去int h,m,s.
2.行走的简单时钟
代码类似
#pragma once
class Clock
{
public:
Clock(int h, int m,int s);
Clock();
Clock(Clock &c);
~Clock() ;
int h, m, s;
void SetTime(int h, int m, int s);
void getTime(int& h, int& m, int& s);
void ShowTime();
void addOneSecond();
};
#include"Clock.h"
#include<Windows.h>
#include<iostream>
using namespace std;
int main()
{
Clock c;
while (1)
{
system("cls");
c.addOneSecond();
c.ShowTime();
Sleep(1000);
}
return 0;
}
#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::getTime(int& h, int& m, int& s)
{
h = this->h;
m = this->m;
s = this->s;
}
void Clock::ShowTime()
{
cout << h << ":" << m << ":" << s << endl;
}
void Clock::addOneSecond()
{
s++;
if (s >= 60)
{
m++;
s = 0;
if (m >= 60)
{
m = 0;
h++;
if (h >= 12)
{
h = 0;
}
}
}
}