C++中的构造函数在类被实例化时自动调用,析构函数在对象消亡时自动被调用,用来释放对象占用的空间。
构造函数与析构函数与类名相同,析构函数在类名前加~。
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;
}
构造函数是可以传递参数的,但析构函数不能,析构函数无参数、无返回值
原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/244369.html