类的组合问题

来源:互联网 发布:我爱你用网络语言表达 编辑:程序博客网 时间:2024/05/16 18:01

问题描述:

      一个类作为另一个类的对象的小例子。分析构造函数和析构函数的调用顺序。

  目的:

     给每个构造函数和析构函数的调用顺序都做了标记,可以清楚的看到每个执行的步骤。

下面就是代码(C++):

***************************************************************************/*   Author:HuangZiBin   Date:2014/4/27   V1.0   Date.h*/#ifndef DATE_H#define DATE_Hclass Date{public:Date(int day=1,int month=1,int year=1);void print()const;~Date();private:int month;int day;    int year;int checkDay(int da);};#endif/*   Author:HuangZiBin   Date:2014/4/27   V1.0   Date.cpp*/#include"Date.h"#include<iostream>using namespace std;Date::Date(int mon,int da,int yea){ if(mon>0&&mon<=12) {  month=mon; } else  {   month=1;   cout<<"Invalid month("<<mon<<")set to 1"<<endl; } year=yea; day=checkDay(da); cout<<"Date object constructor for date:"; print(); cout<<endl;}void Date::print()const{ cout<<month<<"/"<<day<<"/"<<year;}Date::~Date(){ cout<<"Date Object destruct for date:"; print(); cout<<endl;}int Date::checkDay(int da){int dayPreMonth[]={31,29,31,30,31,30,31,31,30,31,30,31};if(da>0&&da<dayPreMonth[month]){ return da;}else  if(month==2&&da==29&&(year%400==0||year%4==0&&year%4!=0))     return da;   cout<<"Invalid month("<<da<<")set to 1"<<endl;   return 1;}  /*   Author:HuangZiBin   Date:2014/4/27   V1.0   Employee.h*/#ifndef EMPLOYEE_H#define EMPLOYEE_H#include"Date.h"class Employee{public:Employee(const char*const,const char*char,const Date&,const Date&);void print()const;~Employee();private:    char firstName[25];char lastName[25];const Date birthDay;const Date hireDate;};#endif/*   Author:HuangZiBin   Date:2014/4/27   V1.0   Employee.cpp*/#include"Date.h"#include"Employee.h"#include<iostream>#include<string>using namespace std;Employee::Employee(const char*const first,const char*const last, const Date& dateOfBrith, const Date&dateOfHire):          birthDay(dateOfBrith),  hireDate(dateOfHire){ int length=strlen(first); length=(length<25)?length:24; strncpy(firstName,first,length); firstName[length]='\0'; length=strlen(last); length=((length<25)?length: 24); strncpy(lastName,last,length); lastName[length]='\0'; cout<<"Employee object constructor"<<firstName<<","<<lastName<<endl;}void Employee::print()const{cout<<firstName<<","<<lastName<<" Hired:";hireDate.print();cout<<"  birthDay:";birthDay.print();cout<<endl;}Employee::~Employee(){ cout<<"Employee object destructor"<<firstName<<","<<lastName<<endl;} /*   Author:HuangZiBin   Date:2014/4/27   V1.0   main.cpp*/#include<iostream>#include"Employee.h"using namespace std;int main(){ Date birth(7,24,1949); Date hire(3,12,1988); Employee manager("Bob","Blue",birth,hire); cout<<endl; manager.print(); cout<<"Test Date constructor with invalid va;ues:\n"; cout<<endl; return 0;}*************************************************************************


     

0 0