第一范文网 - 专业文章范例文档资料分享平台

全国计算机二级C++考试复习知识点汇总

来源:用户分享 时间:2025/6/18 14:18:26 本文由loading 分享 下载这篇文档手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

金 融 学 院 School of Finance

#include iostream.h class Box { private:

int height,width,depth; public:

Box(int ht=2,int wd=3,int dp=4) {

height=ht; width=wd; depth=dp; } ~Box(); int volume() {

return height*width*depth; } };

int main() {

Box thisbox(3,4,5); //初始化 Box defaulbox; //使用默认参数 cout< cout< return 0;

金 融 学 院 School of Finance

}

2.默认构造函数

没有参数或者参数都是默认值的构造函数称为默认构造函数。如果你不提供构造函数,编译器会自动产生一个公共的默认构造函数,这个构造函数什么都不做。如果至少提供一个构造函数,则编译器就不会产生默认构造函数。 3.重载构造函数

一个类中可以有多个构造函数。这些构造函数必须具有不同的参数表。在一个类中需要接受不同初始化值时,就需要编写多个构造函数,但有时候只需要一个不带初始值的空的Box对象。 #include iostream.h class Box { private:

int height,width,depth; public:

Box() { //nothing }

Box(int ht=2,int wd=3,int dp=4) {

height=ht; width=wd; depth=dp; } ~Box(); int volume() {

金 融 学 院 School of Finance

return height*width*depth; } };

int main() {

Box thisbox(3,4,5); //初始化 Box otherbox; otherbox=thisbox; cout< return 0; }

这两个构造函数一个没有初始化值,一个有。当没有初始化值时,程序使用默认值,即2,3,4。

但是这样的程序是不好的。它允许使用初始化过的和没有初始化过的Box对象,但它没有考虑当thisbox给otherbox赋值失败后,volume()该返回什么。较好的方法是,没有参数表的构造函数也把默认值赋值给对象。 class Box {

int height,width,depth; public: Box() {

height=0;width=0;depth=0; }

Box(int ht,int wd,int dp) {

金 融 学 院 School of Finance

height=ht;width=wd;depth=dp; }

int volume() {

return height*width*depth; } };

这还不是最好的方法,更好的方法是使用默认参数,根本不需要不带参数的构造函数。 class Box {

int height,width,depth; public:

Box(int ht=0,int wd=0,int dp=0) {

height=ht;width=wd;depth=dp; }

int volume() {

return height*width*depth; } };

三、析构函数

全国计算机二级C++考试复习知识点汇总.doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/c9tyx546s5d02tjb2ixwe3xy6q955p4014us_3.html(转载请注明文章来源)
热门推荐
Copyright © 2012-2023 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top