预览加载中,请您耐心等待几秒...
1/10
2/10
3/10
4/10
5/10
6/10
7/10
8/10
9/10
10/10

亲,该文档总共41页,到这已经超出免费预览范围,如果喜欢就直接下载吧~

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

C++程序设计主要内容对象的初始化━━使用初始化数据列表对象的初始化━━使用构造函数构造函数构造函数━━在函数体中对各成员数据赋初值【例】(时钟类、构造函数重载) #include<iostream.h> classClock {inthour,minute,second; public: Clock() {hour=0;minute=0;second=0;cout<<“调用不带参的构造函数!\n”;} Clock(inth,intm,ints) {hour=h;minute=m;second=s;cout<<“调用带3个参的构造函数!\n”;} voidsettime(inth,intm,ints) {hour=h;minute=m;second=s;} voidshowtime() {cout<<hour<<“:”<<minute<<“:”<<second<<endl;} }; voidmain() {Clockc1,c2(10,20,30); c1.showtime(); c2.showtime(); c2.settime(8,50,20); c2.showtime();}【例】(矩形类、带默认形参值的构造函数) #include<iostream.h> #include<math.h> classRectangle {floatleft,top,right,bottom; public: Rectangle(floatL=0,floatT=0,floatR=0,floatB=0) {left=L;top=T;right=R;bottom=B;} voidset(floatL,floatT,floatR,floatB) {left=L;top=T;right=R;bottom=B;} voidprint() {cout<<“left=”<<left<<“\ttop=”<<top<<‘\t’; cout<<“right=”<<right<<“\tbottom=”<<bottom<<‘\t’; cout<<“面积=”<<fabs(right-left)*fabs(bottom-top)<<endl;}}; voidmain() {Rectangler0;r0.print(); Rectangler1(10);r1.print(); Rectangler2(10,20);r2.print(); Rectangler3(10,20,30);r3.print(); Rectangler4(10,20,30,40);r4.print(); r0.set(1,2,3,4);r0.print();}默认的构造函数默认的构造函数默认的构造函数this指针━━成员函数中指向当前对象的指针this指针━━成员函数中指向当前对象的指针【例】(学生类、this指针) #include<iostream.h> #include<string.h> classStudent {intid; charname[8]; intscore; public: Student(inti,char*na,ints) {id=i;strcpy(name,na);score=s; cout<<“对象地址=”<<this<<“\t调用构造函数了!\n”;} voidprint() {cout<<“学号:”<<id<<“\t姓名:”<<name<<“\t成绩:”<<score<<endl;} }; voidmain() {Students1(111,“张军”,99); Students2(222,“王红”,88); s1.print(); s2.print();}对象的生存期和作用域【例】(矩形类、构造函数重载、全局对象、static局部对象、auto局部对象) #include<iostream.h> classRectangle {floatleft,top,right,bottom; public: Rectangle(floatL,floatT,floatR,floatB) {left=L;top=T;right=R;bottom=B;cout<<“调用带4个参的构造函数!\n”;} Rectangle(floatL,floatT,floatR) {left=L;top=T;right=R;bottom=0;cout<<“调用带3个参的构造函数!\n”;} Rectangle(floatL,floatT) {left=L;top=T;right=0;bottom=0;cout<<“调用带2个参的构造函数!\n”;} Rectangle(floatL) {left=L;top=0;right=0;bottom=0;cout<<“调用带1个参的构造函数!\n”;}