私有數據:hour, minute, second。公有介面:構造函數(默認 0:0:0)、set_time、get_hour/minute/second、print(輸出 hh:mm:ss am/pm)。
分別用對象、對象指針、對象引用調用成員函數,驗證三種訪問方式等價。
// htime.h
#ifndef TIME_H
#define TIME_H
#include <iostream>
using namespace std;
class Time {
int hour, minute, second;
public:
Time(int h=0, int m=0, int s=0) : hour(h), minute(m), second(s) {}
void set_time(int h, int m, int s) { hour=h; minute=m; second=s; }
int get_hour() const { return hour; }
int get_minute() const { return minute; }
int get_second() const { return second; }
void print() const {
cout << (hour < 12 ? "am " : "pm ")
<< hour << ':' << minute << ':' << second << endl;
}
};
#endif
// main.cpp
#include "htime.h"
int main() {
Time t;
Time* p = &t;
Time& ref = t;
t.set_time(13, 56, 33);
cout << "hour: " << ref.get_hour() << endl; // 引用調用
p->print(); // 指針調用
t.print(); // 對象調用
return 0;
}