C++ 类构造函数 & 析构函数

来源:互联网 发布:java web项目案例 编辑:程序博客网 时间:2024/05/16 05:51
类的构造函数是一种特殊的函数,在创建一个新的对象时调用。
类的析构函数也是一种特殊的函数,在删除所创建的对象时调用。

类的构造函数
类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。
构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。构造函数可用于为某些成员变量设置初始值。

下面的实例有助于更好地理解构造函数的概念:

#include <iostream> using namespace std;  class Line{   public:      void setLength( double len );      double getLength( void );      void setWidth( double wid );      double getWidth( void );      Line(double len,double wid);  // 这是构造函数     private:      double length;      double width;};  // 成员函数定义,包括构造函数Line::Line(double len,double wid){    cout << "Object is being created" << endl;    length=len;    width=wid;}  void Line::setLength( double len ){    length = len;} double Line::getLength( void ){    return length;}void Line::setWidth(double wid){    width=wid;}double Line::getWidth(void){    return width;}// 程序的主函数int main( ){   Line line(7.0,3.5);   double ww=line.getLength();   double ll=line.getWidth();   // 设置长度   cout << "Length of line : " << line.getLength() <<endl;   cout << "Width of line : " << line.getWidth() <<endl;   cout << "Area of line : " << ww*ll <<endl;   return 0;}

运行:

使用初始化列表来初始化字段

假设有一个类 C,具有多个字段 X、Y、Z 等需要进行初始化,同理地,可以使用上面的语法,只需要在不同的字段使用逗号进行分隔,如下所示:
C::C( double a, double b, double c): X(a), Y(b), Z(c)
{
  ....
}
例如上面的那个实例的构造函数的两种写法,效果等同:
写法一:
// 成员函数定义,包括构造函数Line::Line(double len,double wid){    cout << "Object is being created" << endl;    length=len;    width=wid;}
写法二:
// 成员函数定义,包括构造函数Line::Line(double len,double wid):length(len),width(wid){    cout << "Object is being created" << endl;    //length=len;    //width=wid;}
类的析构函数
类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。
析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何参数。析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。
将上述实例简化再加上析构函数有助于更好地理解析构函数的概念:
#include <iostream>using namespace std;  class Line{   public:      void setLength( double len );      double getLength( void );      Line(double len);  // 这是构造函数      ~Line();    //这是析构函数     private:      double length;      double width;};  //定义构造函数Line::Line(double len){    cout << "Object is being created" << endl;    length=len;}//定义析构函数Line::~Line(){    cout << "Object is being deleted" << endl;} //定义成员函数void Line::setLength( double len ){    length = len;} double Line::getLength( void ){    return length;} // 程序的主函数int main( ){     // 设置长度   Line line(7.0);   cout << "Length of line : " << line.getLength() <<endl;   return 0;}

运行结果:



原创粉丝点击