例5.1 分析输出结果。 tdate.h
class TDate { public:
void SetDate(int y,int m, int d)
{ year=y; month=m; day=d;}
int IsLeapYear( )
{return (year%4==0&&year0!=0)|| (year@0==0);} void Print( )
{ cout< < private: int year,month,day; }; #include { TDate date1,date2; date1.SetDate(2004,10,8); date2.SetDate(2005,10,8); int leap1=date1.IsLeapYear( ); cout< int leap2=date2.IsLeapYear( ); cout< 输出: 1 0 2004.10.8 2005.10.8 例5.2 #include Tpoint p1,p2; p1.SetPoint(3,5); p2.SetPoint(8,10); p1.Move(2,1); p2.Move(1,-2); cout<<”x1=”< < cout<<”x2=”< < } 结果: x1=5,y1=6 x2=9,y2=8 例5.3 访问对象的公有成员。 #include void print( ) { cout< void main( ) { Tclass test; test.x=100; test.y=200; test.print( ); } 输出: 100,200 例5.4 用指针访问对象的公有成员。 #include void print( ) { cout< int add(Tclass *ptf) {return (ptf->x+ptf->y);} void main( ) { Tclass test,*pt=new(Tclass); pt->x=100; pt->y=200; pt->print( ); test.x=150; test.y=450; test.print( ); cout<<”x+y=”< 输出: 100,200 150,450 x+y=600 5.3 对象的初始化 5.3.1 构造函数和析构函数 构造函数的格式: 类名::构造函数名(参数表) { } 构造函数的功能: 是在创建对象时,使用给定的值为对象初始化。 析构造函数的格式: 类名::~析构函数名( ) { }