首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 對象指針與引用操作綜合練習

     編輯:關於C++

Time 類設計

私有數據: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;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved