C++ 类的构造函数和析构函数
类的构造函数
类构造函数是类的一个特殊成员函数,每当我们创建该类的新对象时都会执行它。
构造函数的名称与类名完全相同,并且没有任何返回类型,甚至没有 void。构造函数在设置某些成员变量的初始值时非常有用。
示例
以下示例解释了构造函数的概念 -
#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; }
当编译并执行上述代码时,它会产生以下结果 -
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); // 这是构造函数 private: double length; }; // 成员函数定义包括构造函数 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; } // 程序的主函数 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; }
当编译并执行上述代码时,它会产生以下结果 -
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(); // 这是构造函数声明 ~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; }
当编译并执行上述代码时,它会产生以下结果 -
Object is being created Length of line : 6 Object is being deleted