参学:http://www.runoob.com/cplusplus/cpp-constructor-destructor.html
1、构造器(构造函数):
1.定义及意义
class 类名
{
类名(形参列表)
构造体
}
class A
{
A(形参)
{}
}
2.规则
1 )在对象创建时自动调用,完成初始化相关工作。
2 )无返回值,与类名同,
3) 可以重载,可默认参数。
4 )默认无参空体,一经实现,默认不复存在。
3.作用
在类创建对象时,自动调用,完成对类对象的初始化,尤其是动态内存的申请。
屌屌的初始化:初始化列表:注意初始化列表中的被初始化顺序与声明顺序有关 ,与前后赋值无关。
- a.无参构造函数
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); //这是构造函数声明
private:
double length;
};
//成员函数定义,包括构造函数
/**************************************************************/
Line::Line(void)
{
cout << "Object is being created" << endl;
}
/**************************************************************/
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
int main( )
{
Line line;
line.setLength(6.0); //设置长度
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
输出:
- b. 有参构造函数
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len);//这是构造函数声明
private:
double length;
};
//成员函数定义,包括构造函数
/**************************************************************/
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
/*
上面这一个等价于:
Line::Line( double len): length(len)
{
cout << "Object is being created, length = " << len << endl;
}
*/
/***************************************************************/
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
int main( )
{
Line line(10.0);
//获取默认设置的长度
cout << "Length of line : " << line.getLength() <<endl;
//再次设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
- c.多参构造函数(初始化):
class Date
{
public:
Date(int y, int m, int d)
: year(y), month(m), day(d) {}//构造函数(初始化列表)进行类的初始化
private:
int year;
int month;
int day;
};
2、析构器(析构函数):
1.定义
class 类名
{
~类名()
析构体
}
class A
{
~A()
{}
}
2.作用:
对象销毁时期自动调用(1).栈对象离开其作用域。2). 堆对象被手动delete。) ,析构函数并不是删除对象,而在对象销毁前完成的一些清理工作。
3.规则
1 )对象销毁时,自动调用。完成销毁的善后工作。
2 )无返值,与类名同,无参。不可以重载与默认参数。
3 )系统提供默认空析构器,一经实现,不复存在。
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); //这是构造函数声明
~Line(); //这是析构函数声明
private:
double length;
};
//成员函数定义,包括构造函数
/**************************************************************/
Line::Line(void)
{
cout << "Object is being created" << endl;
}
Line::~Line(void)
{
cout << "Object is being deleted" << endl;
}
/**************************************************************/
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
int main( )
{
Line line;
//设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
输出: