C++ 类的构造函数和析构函数
类的构造函数
一个类的构造函数是一个特殊的成员函数,在我们创建该类的新对象时执行。
构造函数的名称与类名完全相同,它没有任何返回类型,甚至不是void。 构造函数可以非常有用,用于为某些成员变量设置初始值。
以下示例解释了构造函数的概念−
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void) {
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
// Main function for the program
int main() {
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
当上述代码被编译和执行时,将产生以下结果:
Object is being created
Length of line : 6
带参数的构造函数
默认构造函数没有参数,但是如果需要,构造函数可以包含参数。这有助于在对象创建时为其赋予初始值,如以下示例所示:
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len) {
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
// Main function for the program
int main() {
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
当上面的代码被编译和执行时,会产生以下结果 −
Object is being created, length = 10
Length of line : 10
Length of line : 6
使用初始化列表来初始化字段
在参数化构造函数的情况下,您可以使用以下语法来初始化字段:
Line::Line( double len): length(len) {
cout << "Object is being created, length = " << len << endl;
}
上述语法与下述语法相等:
Line::Line( double len) {
cout << "Object is being created, length = " << len << endl;
length = len;
}
如果对于一个类C,你有多个要初始化的字段X、Y、Z等等,那么可以使用相同的语法,并用逗号分隔字段,如下所示―
C::C( double a, double b, double c): X(a), Y(b), Z(c) {
....
}
类析构函数
析构函数是一个特殊的类成员函数,当其类的对象超出范围或者一个指向该类对象的指针使用delete表达式时,该析构函数会被执行。
析构函数的名称与类的名称相同,前面加上一个波浪号(~),它既不能返回值也不能带有任何参数。在程序结束前释放资源时,析构函数非常有用,比如关闭文件、释放内存等。
以下示例解释了析构函数的概念:
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
// Member functions definitions including constructor
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;
}
// Main function for the program
int main() {
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
当上述代码被编译和执行时,它产生以下结果 –
Object is being created
Length of line : 6
Object is being deleted