- //Clock.h
- # ifndef _CLOCK_H_
- # define _CLOCK_H_
- class Clock
- {
- public:
- Clock(int hour = 0,int minute = 0, int seond = 0);
- ~Clock();
- void Display();
- void Init(int hour, int minute, int second);
- void Update();
- int GetHour();
- int GetMinute();
- int GetSecond();
- void SetHour(int hour);
- void SetMinute(int minute);
- void SetSecond(int Second);
- private:
- int hour_;
- int minute_;
- int second_;
- };
- # endif //_CLOCK_H_
- //Clock.cpp
- # include "Clock.h"
- # include <iostream>
- using namespace std;
- void Clock::Display()
- {
- cout << hour_ <<":"<<minute_<<":"<<second_<<endl;
- }
- //初始化列表,初始化段
- Clock::Clock(int hour, int minute, int second):hour_(hour),minute_(minute),second_(second)
- {
- //hour_ = hour; 不是真正的初始化
- //minute_ = minute;只是简单的赋值
- //second_ = second;
- cout <<"Clock::Clock" << endl;//普通计算段
- }
- Clock::~Clock()
- {
- cout<< "Clock::~Clock "<< endl;
- }
- void Clock::Init(int hour, int minute, int second)
- {
- hour_ = hour;
- minute_ = minute;
- second_ = second;
- }
- void Clock::Update()
- {
- second_++;
- if(second_ == 60)
- {
- minute_++;
- second_ = 0;
- }
- if(minute_ == 60)
- {
- hour_++;
- minute_ = 0;
- }
- if(hour_ == 24)
- {
- hour_ = 0;
- }
- }
- int Clock::GetHour()
- {
- return hour_;
- }
- int Clock::GetMinute()
- {
- return minute_;
- }
- int Clock::GetSecond()
- {
- return second_;
- }
- void Clock::SetHour(int hour)
- {
- hour_ = hour;
- }
- void Clock::SetMinute(int minute)
- {
- minute_ = minute;
- }
- void Clock::SetSecond(int second)
- {
- second_ = second;
- }
- # include "Clock.h"
- int main(void)
- {
- Clock c(10,10,10);
- c.Display();
- return 0;
- }
- # ifndef _TEST_H_
- # define _TEST_H_
- class Object
- {
- public:
- enum E_TYPE
- {//对所有对象来说都是常量
- TYPE_A = 100,
- TYPE_B = 200
- };
- public:
- Object(int num);
- ~Object();
- void DisplayKNum();
- private:
- int num_;
- const int kNum_;//仅限于某个对象是常量
- int& refNum_;
- };
- # endif //_TEST_H_
- # include "Test_1.h"
- # include <iostream>
- using namespace std;
- Object::Object(int num = 0) : num_(num),kNum_(num_),refNum_(num_)
- { //本质上是赋值
- //Knum = 100; error const的初始化必须在初始化列表中初始化
- //refNum_ = num_; error 引用成员的初始化必须在初始化列表中初始化
- cout << "Object "<<num_ << "..." << endl;
- }
- void Object::DisplayKNum()
- {
- //cout << "kNum = " << kNum_ << endl;
- cout << "kNum = " << kNum_ << endl;
- }
- Object::~Object()
- {
- cout << "~Object "<<num_<<"..." << endl;
- }
- #include "Test_1.h"
- # include <iostream>
- using namespace std;
- int main(void)
- {
- Object obj1(10);
- Object obj2(20);
- obj1.DisplayKNum();
- obj2.DisplayKNum();
- //针对类内部是常量,而对于所有对象都是常量要用枚举
- cout <<obj1.TYPE_A<<endl;
- cout <<obj2.TYPE_A<<endl<<endl;
- //适用于任何对象,要用枚举常量
- cout <<Object::TYPE_A<<endl;
- cout <<Object::TYPE_B<<endl;
- return 0;
- }