1#include <iostream>2#include <stdlib.h>3 using namespacestd;4 classtdate5 {6 Public:7Tdate (intmm=0,intDd=0,intyy=0);8~tdate ()9 {Tencout<<"Call destructor.\n"; One } A voidTdate::setdate (intMintDinty);//the constructor parameter sets the default value - voidprint () - { thecout<<"month="<<month<<", day="<<day<<", year="<<year<<"\ n"; - } - protected: - intmonth,day,year; + }; -Tdate::tdate (intMmintDdintyy) + { AMonth=mm; atday=DD; -Year=yy; -cout<<"Call constructor.\n"; - } - voidTdate::setdate (intMintDinty) - { in if(m>0&&m< -) -Month=m; to if(d>0&&d< +) +day=D; - if(y>0&&y< the) theYear=y; * } $ intMain ()Panax Notoginseng { -Tdate *pd1,*pd2; thepd1=NewTdate (1,1, -);//to create a dynamic object, the constructor is called +Pd1->print ();//You can only use the pointer to access the members of the object APd2=NewTdate ( A, to, -);//to create a dynamic object, the constructor is called the if(!PD2)//If allocating heap memory is unsuccessful + { -cout<<"Heap error!\n";//Output error message $Exit1);//Terminate program run $ } - Else//If allocating heap memory succeeds -Pd2->setdate (8,8, -);//Call function Reset Date thePd2->print (); - DeletePD1;//Deleting a Dynamic object invokes a destructorWuyi DeletePD2;//Deleting a Dynamic object invokes a destructor the}
C + + Object-oriented jobs 1