1. 定义一个时间类,类中有3个私有数据成员(Hour,Minute,Second)和两个公有成员函数(SetTime和Print_Time)。SetTime根据传递的3个参数为对象设置时间;Print_Time负责将对象表示的时间输出。
定义一个时间类对象,设置时间为9点20分30秒并显示该时间。
#include<string.h> #include<iostream> using namespace std; class Timee { private: int hour; int minute; int second; public: void settime(int h,int m,int s); void printtime(); }; void Timee::settime(int h,int m,int s) { hour=h; minute=m; second=s; } void Timee::printtime() { cout<<hour<<" "<<minute<<" "<<second<<endl; } int main() { Timee a; a.settime(9,20,30); a.printtime(); return 0; }
2. 使用构造函数代替上面的SetTime成员函数,并在主函数中使用构造函数设置时间为10点40分50秒,并显示该时间。
#include<string.h> #include<iostream> using namespace std; class Timee { private: int hour; int minute; int second; public: Timee(int h,int m,int s); void printtime(); }; Timee::Timee(int h,int m,int s) { hour=h; minute=m; second=s; } void Timee::printtime() { cout<<hour<<" "<<minute<<" "<<second<<endl; } int main() { Timee a(10,40,50); a.printtime(); return 0; }
3. 重载时间类的构造函数(不带参数),使得小时、分、秒均为0。
#include<string.h> #include<iostream> using namespace std; class Timee { private: int hour; int minute; int second; public: Timee(int h,int m,int s); Timee(); void printtime(); }; Timee::Timee(int h,int m,int s) { hour=h; minute=m; second=s; } Timee::Timee() { hour=0; minute=0; second=0; } void Timee::printtime() { cout<<hour<<" "<<minute<<" "<<second<<endl; } int main() { Timee a; a.printtime(); return 0; }
4. 在时间类的析构函数中输出“Good bye!”。
#include<string.h> #include<iostream> using namespace std; class Timee { private: int hour; int minute; int second; public: Timee(int h,int m,int s); Timee(); ~Timee(); void printtime(); }; Timee::Timee(int h,int m,int s) { hour=h; minute=m; second=s; } Timee::Timee() { hour=0; minute=0; second=0; } Timee::~Timee() { cout<<"Good bye!"<<endl; } void Timee::printtime() { cout<<hour<<" "<<minute<<" "<<second<<endl; } int main() { Timee a; a.printtime(); return 0;//程序结束自动调用析构函数; }
5. 定义拷贝构造函数并使用。在时间类中定义一个静态数据成员,记录当前的年份2017年。
#include<string.h> #include<iostream> using namespace std; class Timee { private: int hour; int minute; int second; static int yearr; public: Timee(int h,int m,int s); Timee(); ~Timee(); Timee(Timee & a); void printtime(); }; Timee::Timee(int h,int m,int s) { hour=h; minute=m; second=s; } Timee::Timee() { hour=0; minute=0; second=0; } Timee::~Timee() { cout<<"Good bye!"<<endl; } Timee::Timee(Timee & a) { hour=a.hour; minute=a.minute; second=a.second; } void Timee::printtime() { cout<<yearr<<" "<<hour<<" "<<minute<<" "<<second<<endl; } int Timee::yearr=2017;//必须在定义类的文件中对静态成员变量进行一次声明或初始化; int main() { Timee a(9,20,20); Timee b(a); a.printtime(); b.printtime(); return 0; }