实现一个电子时钟类,其构造函数接受当前系统时间,以秒为单位持续运行
#include <iostream>
#include <unistd.h> // linux下使用sleep函数需要引用这个头文件
#include <iomanip> // 流格式控制符---使用setw函数
using namespace std;
class Clock
{
public:
Clock(time_t now)
{
tm *local = localtime(&now);
m_hour = local->tm_hour;
m_min = local->tm_min;
m_sec = local->tm_sec;
}
void run(void)
{
for (;;)
{
show();
tick();
}
}
private:
void show(void)
{
cout << '\r' << setfill('0') // 不到两位填0
<< setw(2) << m_hour << ":" // 设置2位域宽,防止出现最后的秒数没有覆盖的情况
<< setw(2) << m_min << ":"
<< setw(2) << m_sec << flush;
}
void tick(void)
{
sleep(1);
if (++m_sec == 60)
{
m_sec = 0;
if (++m_min == 60)
{
m_min = 0;
if (++m_hour = 24)
{
m_hour = 0;
}
}
}
}
int m_hour;
int m_min;
int m_sec;
};
int main(void)
{
Clock clock(time(NULL)); // 返回time_t类型变量,即1970年最开始的那个时间
clock.run();
return 0;
}
实现一个最多保存100个整型数的容器类,通过at(size_t index)成员函数接受从0开始的下标,要求根据容器的常属性返回其中元素的左值或右值。
#include <iostream>
using namespace std;
class A100
{
public:
int &at(size_t i) // 引用作为返回值,非常容器返回左值
{
return m_arr[i];
}
const int &at(size_t i) const // 常容器返回右值
{
return this->m_arr[i];
}
private:
int m_arr[100];
};
int main(void)
{
A100 a;
a.at(0) = 100;
a.at(1) = 200;
a.at(0)++;
--a.at(1);
cout << a.at(0) << " " << a.at(1) << endl;
const A100* p = &a;
cout << p->at(0) << " " << p->at(1) << endl;
return 0;
}