c++课件第九章关于类和对象的进一步讨论.doc

c++课件第九章关于类和对象的进一步讨论.doc

PAGE 1 第9章 关于类和对象的进一步讨论 9.1构造函数 9.1.1对象的初始化 在建立一个对象时,常常要做一些初始化工作,例如数据成员赋初值等。 类的数据成员是不能在声明类时初始化的。 #include iostream using namespace std; class Time { int hour;//int hour=0; int minute; int sec; }; void main() { Time t1={14,56,30}; } error C2552: t1 : non-aggregates cannot be initialized with initializer list 上面这种写法是错误的。如果数据成员是公有的,则可以用初始化列表形式初始化。 #include iostream using namespace std; class Time { public: int hour; int minute; int sec; }; void main() { Time t1={14,56,30}; } 9.1.2构造函数的作用 C++提供构造函数来处理对象的初始化,构造函数是一种特殊的成员函数,不需要用户来调用它,而是建立对象时自动执行。构造函数与类同名,并且没有返回类型。构造函数可以根据需要进行重载。 例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.set_time(); t1.show_time(); Time t2; t2.show_time(); return 0; } 10 25 54 10:25:54 0:0:0 9.1.3带参数的构造函数 例9.2 有两个长方体,其长、宽、高分别为(1)12,20,25(2)15,30,21。求它们的体积。编一个基于对象的程序,在类中用带参数的构造函数。 #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); coutThe volume of box1 is box1.volume()endl; Box box2(15,30,21); coutThe volume of box2 is box2.volume()endl; return 0; } The volume of box1 is 9000 The volume of box2 is 9450 9.1.4用参数初始化表对数据成员初始化 #include iostream using namespace std; class Box { public: Box(int h,int w ,int len): height(h),width(w),length(len){} int volume(); private: int height; int width; int length; }; int Box::volume() { return(height*width*length); } int main() { Box box1(12,25,30); coutThe volume of box1 is box1.volume()endl; Box box2(15,30,21);

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档