700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 类和对象的基础2——对象的生与死(构造函数和析构函数)

类和对象的基础2——对象的生与死(构造函数和析构函数)

时间:2019-04-09 01:32:51

相关推荐

类和对象的基础2——对象的生与死(构造函数和析构函数)

1、构造函数:对对象进行初始化;析构函数:对对象进行销毁,释放内存。

注:(1)构造函数没有返回值,构造函数名必须和类名相同;

(2)构造函数可以带一个或多个参数,可以实现函数的重载;

(3)析构函数名必须和类名相同。

2、构造函数的作用:实现数据成员的初始化。

3、实例:定义一个学生类,用构造函数进行初始化,打印出学生信息,最后用析构函数销毁对象。

/***构造函数和析构函数***/#include <iostream>using namespace std;class student{public:<span style="white-space:pre"></span>char name[4];<span style="white-space:pre"></span>short number;<span style="white-space:pre"></span>double average_score(int chinese,int math,int english);<span style="white-space:pre"></span>student(); //构造函数<span style="white-space:pre"></span>~student(); //析构函数private:<span style="white-space:pre"></span>int rank(int num);<span style="white-space:pre"></span>char adress[20];} ;double student::average_score(int chinese,int math,int english){<span style="white-space:pre"></span>double average_score;<span style="white-space:pre"></span>average_score = (chinese + math + english)*1.0/3;<span style="white-space:pre"></span>return average_score;}student::student() //构造函数的实现{<span style="white-space:pre"></span>name[0] = 'k';name[1] = 'i';name[2] = 'n';name[3] = 'g';<span style="white-space:pre"></span>//char name[5] = "king"; //为什么这样会乱码,而且四个字符为什么要定义五个字节的大小,四个的话就太小了,是因为加了结束符\0吗<span style="white-space:pre"></span>number = 007;<span style="white-space:pre"></span>char address[20] = "hu";}student::~student() //析构函数的实现{<span style="white-space:pre"></span>cout<<"Deconstruct the student!"<<endl;}int student::rank(int num){<span style="white-space:pre"></span>int rank;<span style="white-space:pre"></span>rank = num;<span style="white-space:pre"></span>return rank;}void main(void){<span style="white-space:pre"></span>student student1;//定义对象,并有构造函数进行初始化<span style="white-space:pre"></span>double averscore;<span style="white-space:pre"></span>cout<<"输出学生的信息"<<endl;<span style="white-space:pre"></span>cout<<"姓名:"<<student1.name<<endl; //打印名字,为什么打印出来时乱码???<span style="white-space:pre"></span>cout<<"学号:"<<student1.number<<endl; //打印学号<span style="white-space:pre"></span>averscore = student1.average_score(81,80,80);<span style="white-space:pre"></span>cout<<"平均成绩是:"<<averscore<<endl;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。