《实验报告05》
类和对象(二)
代码使用说明:
在新建项目里对应的 头文件 或 源文件 里,新建对应的文件,并把代码复制进去即可。
创建效果如图:
代码如下:
// 1、stdafx.h文件
#pragma once
#include <iostream>
#include <string>
using namespace std;
// 2、Time.h文件
#include "stdafx.h"
class Time
{
public:
Time(void);
~Time(void);
void getTime(int Hour, int Minute, int Second);
void Update();
void show24();
void show12();
private:
int hour;
int minute;
int second;
};
// 3、Time.cpp文件
#include "Time.h"
Time::Time(void)
{
hour = 0;
minute = 0;
second = 0;
}
Time::~Time(void)
{
}
void Time::getTime(int Hour, int Minute, int Second)
{
hour = Hour;
minute = Minute;
second = Second;
cout << "测试样例为:" << hour << ":" << minute << ":" << second << endl;
}
void Time::Update()
{
if (hour < 0 || hour > 23)hour = 0;
if (minute < 0 || minute > 59)minute = 0;
if (second < 0 || second > 59)second = 0;
}
void Time::show24()
{
cout << "24小时格式为:";
cout << hour << ":" << minute << ":" << second << endl << endl ;
}
void Time::show12()
{
cout << "12小时格式为:";
if (hour == 0 || hour == 24)cout << "12" << ":" << minute << ":" << second << " am" << endl;
else if (hour >= 12)cout << hour - 12 << ":" << minute << ":" << second << " pm" << endl;
else if (hour < 12)cout << hour << ":" << minute << ":" << second << " am" << endl;
}
// 4、项目测试源文件
#include "stdafx.h"
#include "Time.h"
int main()
{
system("color F0");
Time time1, time2, time3;
//测试样例time1
int Hour = 5, Minute = 65, Second = 35;
time1.getTime(Hour, Minute, Second);
time1.Update();
time1.show12();
time1.show24();
//测试样例time2
Hour = 25, Minute = 35, Second = 70;
time2.getTime(Hour, Minute, Second);
time2.Update();
time2.show12();
time2.show24();
//测试样例time3
Hour = 15, Minute = 25, Second = 35;
time3.getTime(Hour, Minute, Second);
time3.Update();
time3.show12();
time3.show24();
}