Maplewing

10/17 C++: Class Time

Oct 17th, 2015
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Time{
  5.     private:
  6.         // 資料(變數部分)
  7.         int hour;
  8.         int minute;
  9.         int second;
  10.    
  11.     public:
  12.         // 操作(函式部分)
  13.         void print(){
  14.             cout << hour << "時" << minute << "分" << second << "秒" << endl;
  15.         }
  16.             // 建構式
  17.             Time(){
  18.                 hour = 0;
  19.                 minute = 0;
  20.                 second = 0;
  21.             }
  22.            
  23.             Time(int h, int m, int s){
  24.                 setHour(h);
  25.                 setMinute(m);
  26.                 setSecond(s);
  27.             }
  28.        
  29.        
  30.             // Set函式
  31.             void setHour(int h){
  32.                 if( h < 0 || h >= 24 ){
  33.                     cout << "輸入錯誤" << endl;
  34.                     hour = 0; // 給予預設值
  35.                 }
  36.                 else{
  37.                     hour = h;
  38.                 }
  39.             }
  40.            
  41.             void setMinute(int m){
  42.                 if( m < 0 || m >= 60 ){
  43.                     cout << "輸入錯誤" << endl;
  44.                     minute = 0; // 給予預設值
  45.                 }
  46.                 else{
  47.                     minute = m;
  48.                 }
  49.             }
  50.            
  51.             void setSecond(int s){
  52.                 if( s < 0 || s >= 60 ){
  53.                     cout << "輸入錯誤" << endl;
  54.                     second = 0; // 給予預設值
  55.                 }
  56.                 else{
  57.                     second = s;
  58.                 }
  59.             }
  60.            
  61.             // Get函式
  62.             int getHour(){
  63.                 return hour;
  64.             }
  65.            
  66.             int getMinute(){
  67.                 return minute;
  68.             }
  69.            
  70.             int getSecond(){
  71.                 return second;
  72.             }
  73.            
  74.        
  75.        
  76.        
  77. };
  78.  
  79. int main(){
  80.     /*
  81.     Time t1 = {89, 104, 253};
  82.     Time t2;
  83.     t2.hour = 104;
  84.     t2.minute = 32;
  85.     t2.second = 58;
  86.     */
  87.     Time t1;
  88.     t1.setHour(104);
  89.     t1.setMinute(11);
  90.     t1.setSecond(25);
  91.    
  92.     t1.print();
  93.    
  94.     Time t2(12, 23, 3500);
  95.     t2.print();
  96.    
  97.     cout << t1.getHour() << endl;
  98.    
  99.     return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment