第10章类和对象例子.docVIP

  • 2
  • 0
  • 约 22页
  • 2017-09-02 发布于浙江
  • 举报
第10章类和对象例子

例10.4 定义并测试长方形类CRect,长方形是由左上角坐标(left, top)和右下角坐标(right, bottom)组成。 #include iostream.h #include math.h class CRect //定义长方形类 { private: int left, top, right, bottom ; public: void setcoord(int, int, int, int); void getcoord(int *L, int *T, int *R, int *B) //注意:形参为指针变量 { *L = left; *T = top; *R = right; *B = bottom; } void print(void) { coutArea = ; coutabs(right-left)* abs(bottom-top)endl; } }; void CRect::setcoord(int L, int T, int R, int B) { left=L; top=T; right=R; bottom=B; } void main(void) { CRect r, rr; int a, b, c, d ; r.setcoord(100, 300, 50, 200); r.getcoord( a, b, c, d ); //用变量的指针做参数,带回多个结果 cout left= a endl; cout top= b endl; cout right= c endl; cout bottom= d endl; r.print( ); rr = r; //对象可整体赋值 rr.print( ); } 运行结果: left=100 top=300 right=50 bottom=200 Area = 5000 Area = 5000 返回ppt讲稿 例10.5 定义日期类,利用构造函数初始化数据成员。程序放在头文件date.h中,如下: #include iostream.h class Date { int Year, Month, Day; public: Date( ) //重载构造函数 1 { Year=2010; Month=5; Day=1; } Date(int y) //重载构造函数 2 { Year=y; Month=5; Day=1; } Date(int y, int m) //重载构造函数 3 { Year=y; Month=m; Day=1; } Date(int y, int m, int d) //重载构造函数 4 { Year=y; Month=m; Day=d; } void ShowDate( ) { cout Year.Month.Dayendl; } }; 主函数源文件为Li1005.cpp,内容如下: #include date.h void main( ) { Date d1; //自动调用构造函数 1 Date d2(2010); //自动调用构造函数 2 Date d3(2010, 10); //自动调用构造函数 3 Date d4(2010, 10, 6); //自动调用构造函数 4 d1.ShowDate( ); d2.ShowDate( ); d3.ShowDate( ); d4.ShowDate( ); } 运行结果是: 2010.5.1 2010.5.1 2010.10.1 2010.10.6 当然我们可以定义带缺省值的构造函数,将上述构造函数简化,下述程序的功能与上述程序相当: #include iostream.h class Date { int Year, Month, Day; public: Date(int y=2010, int m=5, int d=1) //带参数缺省值的构造函数 { Year=y; Month=m; Day=d; } void ShowDate( ) { cout Year.Month.Dayendl; } }; void main( ) { Date d1, d2(2010), d3(2010, 10), d4(2010, 10, 6); d1.ShowDate( ); d2.Sho

文档评论(0)

1亿VIP精品文档

相关文档