




如果您无法下载资料,请参考说明:
1、部分资料下载需要金币,请确保您的账户上有足够的金币
2、已购买过的文档,再次下载不重复扣费
3、资料包下载后请先用软件解压,在使用对应软件打开
程序设计实习第十四讲类与对象III类和数据抽象(三)课堂问题转换构造函数Complexc1;//Complex(0)c1={0,0}; Complexc2=2;//Complex(2)c2={2,0}; Complexc3=2.5;//Complex(2.5)c3={2.5,0}; intmain() { printf("c1=%f+%fi\n",c1.real,c1.imag); printf("c2=%f+%fi\n",c2.real,c2.imag); printf("inmain\n"); c1=4; printf("endmain\n"); return0; } 输出: IntConstructorcalled IntConstructorcalled FloatConstructorcalled c1=0.000000+0.000000i c2=2.000000+0.000000i inmain IntConstructorcalled Destructorcalled临时对象消亡 endmain Destructorcalled Destructorcalled Destructorcalled常量对象和常量方法在类的成员函数说明后面可以加const关键字,则该成员函数成为常量成员函数 classSample{ private: intvalue; public: voidSetValue()const{ value=0;//wrong //常量方法内部不能改变属性的值 } }; constSampleObj;//常量对象上可以使用常量成员函数 Obj.SetValue(); 在定义常量成员函数和说明常量成员函数时都应该使用const关键字 classSample{ private: intvalue; public: voidSetValue()const; }; voidSample::SetValue()const{//此处不使用const会 //导致编译出错 cout<<value; }常量成员函数的重载 classbase1{ private: inti; public: base1(){i=0;} }; classbase2{ private: inti; public: base2(intn){i=n;} }; classBig{ private: intn; base1b1; base2b2,b3; public: Big(intn):b1(n),b2(1),b3(2) { } }; Bigb;//如果不定义构造函数则编译出错classBig{ private: intn; base1b1; base2b2,b3; public: Big(intn):b1(n),b2(n),b3(2) { } }; Bigb(5);//如果不定义构造函数则编译出错成员对象初始化封闭类构造/析构函数执行过程封闭类例子程序: #include<iostream>usingnamespacestd; classCIn1{ public: CIn1(intn){cout<<"CIn1contructor"<<endl;} ~CIn1(){cout<<"CIn1destructor"<<endl;} }; classCIn2{ public: CIn2(intn){cout<<"CIn2contructor"<<endl; } ~CIn2(){cout<<"CIn2destructor"<<endl;} }; classCOut{ private: CIn2objCIn2;CIn1objCIn1; public: COut():objCIn1(1),objCIn2(2) { cout<<"COutcontructor"<<endl; } ~COut(){ cout<<"COutdestructor"<<endl; } }; intmain() { COutobjCOut; return0; }输出结果: CIn2constructor CIn1constructor COutconstructor COutDestructor CIn1Destructor CIn2Destructorclassexample{ private: constintnum; int&ret; intvalue; public: example(intn,intf):num(n),ret(f),value(4) { } };

王子****青蛙
实名认证
内容提供者


最近下载
最新上传
浙江省宁波市2024-2025学年高三下学期4月高考模拟考试语文试题及参考答案.docx
汤成难《漂浮于万有引力中的房屋》阅读答案.docx
四川省达州市普通高中2025届第二次诊断性检测语文试卷及参考答案.docx
山西省吕梁市2025年高三下学期第二次模拟考试语文试题及参考答案.docx
山西省部分学校2024-2025学年高二下学期3月月考语文试题及参考答案.docx
山西省2025年届高考考前适应性测试(冲刺卷)语文试卷及参考答案.docx
全国各地市语文中考真题名著阅读分类汇编.docx
七年级历史下册易混易错84条.docx
湖北省2024-2025学年高一下学期4月期中联考语文试题及参考答案.docx
黑龙江省大庆市2025届高三第三次教学质量检测语文试卷及参考答案.docx