//3.10含有构造函数和析构函数
#include<iostream>
using namespace std;
class Score{
public:
Score(int m=0,int f=0);//声明构造函数,带有默认参数
~Score();
void setScore(int m,int f);
void showScore();
private:
int mid_exam;
int fin_exam;
};
Score::Score(int m,int f):mid_exam(m),fin_exam(f)
{
cout<<"构造函数使用中……"<<endl;
}
Score::~Score()
{
cout<<"析构函数使用中"<<endl;
}
void Score::setScore(int m,int f)
{
mid_exam=m;
fin_exam=f;
}
inline void Score::showScore()
{
cout<<"期中:"<<mid_exam<<endl<<"期末:"<<fin_exam<<endl;
}
int main()
{
Score o1(80,88);
cout<<endl<<"成绩输出:";
o1.showScore();
o1.setScore(90,98);
cout<<endl<<"成绩输出:";
o1.showScore();
return 0; //在撤销对象o1时,使用析构函数,释放储存的空间
}
说明:在以下情况中,当对象的生命周期结束时,析构函数会被自动调用:
( 1)如果定义了一个全局对象,则在程序流程离开其作用域(如main()函数结束或调用exit()文)时,调用该全局对象的析构函数。
(2)如果一个对象被定义在一个函数体内,则当这个函数被调用结束时,该对象应该释放,勾函数被自动调用。
(3)若一个对象是使用new运算符动态创建的,在使用delete运算符释放它时, delete会自周用析构函数。