}
void TDate2::Print( )
{ cout< #include cout<<”d is “; d.Print( ); d.SetDate(2004,10,8); cout<<”d is “; d.Print( ); } 输出: Constructor called. d is -858993460,-858993460,-858993460 d is 2004.10.8 Destructor called. 例5.7 重新定义日期类 //tdate3.h class TDate3 { public: TDate3(int,int,int); ~TDate3( ); void SetDate(int y,int m,int d); void IsLeapYear( ); void Print( ); private: int year,month,day; }; TDate3::TDate3(int y,int m,int d) { year=y; month=m; day=d; cout< <<”:Constructor called.\\n”;} TDate3:: ~TDate3( ) { cout< <<”:Destructor called.\\n”;} void TDate3::SetDate(int y,int m,int d) { year=y; month=m; day=d; } void TDate3::IsLeapYear( ) { if(year%4==0 && year0!=0 || year@0==0) cout<<”Is leap year.\\n”; else cout<<”Is not leap year.\\n”; } void TDate3::Print( ) { cout< #include {TDate3 d1(2000,5,1); TDate3 d2(2001,10,1); d1.SetDate(1998,6,15); d1.Print( ); d1.IsLeapYear( ); d1.SetDate(2000,9,23); d1.Print( ); d1.IsLeapYear( );} 输出: 2000.5.1:Constructor called. 2001.10.1:Constructor called. 1998.6.15 Is not leap year. 2000.9.23 Is leap year. 2001.10.1:Destructor called. 2000.9.23:Destructor called. 对象的构造和析构次序是相反的,先建立的对象后析构。 例5.8 定义图书卡片类。 #include Card(char *t,char *name, int num); void show( ); private: char title[80]; char author[40]; int number; }; Card::Card(char *t,char *name, int num) { strcpy(title,t); strcpy(author,name); number=num; } void Card::show( ) { cout<<”Title:”< { Card book1(“Basic”,”Tang”,10); Card book2(“FORTRAN”,”Wang”,20); book1.show( ); book2.show( ); } 输出: Title:Basic Author:Tang