第09章关于类和对象进一步讨论11111.pptVIP

  • 5
  • 0
  • 约1.42万字
  • 约 112页
  • 2017-06-09 发布于河南
  • 举报
第09章关于类和对象进一步讨论11111

第9章 关于类和对象的进一步讨论;本章内容;9.1 构造函数;9.1.1 对象的初始化;9.1.2 构造函数的作用;例9.1 在例8.3基础上定义构造成员函数。 #include iostream using namespace std; class Time { public: Time( ) //定义构造成员函数,函数名与类名相同 {hour=0; //利用构造函数对对象中的数据成员赋初值 minute=0; sec=0; } void set_time( ); //函数声明 void show_time( ); //函数声明 private: int hour; //私有数据成员 int minute; int sec; };;void Time∷set_time( ) {cinhour; cinminute; cinsec; } void Time∷show_time( ) {couthour″:″minute″:″secendl; } int main( ) { Time t1; //建立对象t1,同时调用构造函数t1.Time( ) t1.set_time( ); //对t1的数据成员赋值 t1.show_time( ); //显示t1的数据成员的值 Time t2; //建立对象t2,同时调用构造函数t2.Time( ) t2.show_time( ); //显示t2的数据成员的值 return 0; };9.1.2 构造函数的作用;9.1.3 带参数的构造函数;9.1.3 带参数的构造函数;9.1.3 带参数的构造函数;#include iostream using namespace std; class Box {public: Box(int,int,int); //声明带参数的构造函数 int volume( ); //声明计算体积的函数 private: int height; int width; int length; }; Box∷Box(int h,int w,int len) //在类外定义带参数的构造函数 {height=h; width=w; length=len; };int Box∷volume( ) //定义计算体积的函数 {return(height*width*length); } int main( ) { Box box1(12,25,30); //建立对象box1,并指定box1长、宽、高的值 cout″The volume of box1 is ″box1.volume( )endl; Box box2(15,30,21); //建立对象box2,并指定box2长、宽、高的值 cout″The volume of box2 is ″box2.volume( )endl; return 0; };9.1.4 用参数初始化表对数据成员初始化;9.1.5 构造函数的重载;#include iostream using namespace std; class Box {public: Box( ); //声明一个无参的构造函数 Box(int h,int w,int len):height(h),width(w),length(len){ }//声明一个有参的构造函数,用参数的初始化表对数据成员初始化 int volume( ); private: int height; int width; int length; }; Box∷Box( ) //定义一个无参的构造函数 {height=10; width=10; length=10; };int Box∷volume( ) {return(height*width*length); } int main( ) { Box box1; //建立对象box1,不指定实参 cout″The volume of box1 is ″box1.volume( )endl; Box box2(15,30,25); //建立对象box2,指定3个实参 cout″The volume of box2 is ″box2.volume( )endl; return 0; };9.1.5 构造函数的重载;9.1.6 使用默认参数的构造函数;#in

文档评论(0)

1亿VIP精品文档

相关文档