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);
您可能关注的文档
- 度职业教育优质数字资源建设指南.doc
- 钢铁工程专业英语词汇汇总.doc
- 工作总结历史教学工作总结.doc
- 国际学术交流英语-外研版部分.doc
- 国学知识竞赛试题题库--文学、民俗、历史、科技、军事、艺术、哲学、生活常识总汇.doc
- 基于VB与MAPX控件的南海市道路交通事故地理信息系统的交通事故地理信息系统的开发.doc
- 近代物理实验2-1盖革-米勒计数器及核衰变统计规律.doc
- 经典英语学习经验分享.docx
- 考博英语考博英语阅读理解题型及解题技巧讲义.doc
- 考研数学数学三历年真题解析2004-2012年.doc
- 2026福建龙岩市公安局永定分局招聘招聘警务辅助人员34人备考题库附答案.docx
- 2026江苏南通开放大学兼职教师招聘备考题库含答案.docx
- 2026贵州六盘水市青少年活动中心第一批招聘外聘教师7人备考题库含答案.docx
- 2025年宁波象山县卫生健康系统公开招聘编外人员36人备考题库含答案.docx
- 2026四川天府银行社会招聘备考题库必考题.docx
- 2026广东中山市公安局南头分局招聘辅警3人备考题库及答案1套.docx
- 2025年磨憨出入境边防检查站四季度招聘边境管控专职辅警(11人)备考题库含答案.docx
- 2026年徽商银行总行金融科技岗社会招聘备考题库必考题.docx
- 2025菏泽照昕外国语学校招聘8人备考题库含答案.docx
- 2025四川凉山州甘洛县人力资源和社会保障局从服务期满的“三支一扶”项目人员中考核招聘事业单位工作人.docx
原创力文档

文档评论(0)