第5章 类和对象1(3)

2019-02-15 16:06

例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 #include”tdate.h” void main( )

{ 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 #include”tpoint.h” void main( ) {

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 class Tclass { public: int x,y;

void print( )

{ cout<

void main( ) { Tclass test; test.x=100;

test.y=200; test.print( ); }

输出: 100,200

例5.4 用指针访问对象的公有成员。 #include class Tclass { public: int x,y;

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 构造函数和析构函数

构造函数的格式:

类名::构造函数名(参数表) { }

构造函数的功能:

是在创建对象时,使用给定的值为对象初始化。

析构造函数的格式: 类名::~析构函数名( ) { }


第5章 类和对象1(3).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:同济大学环境科学与工程学院2011年硕士研究生入学考试试卷A+B组

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: