类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。
    析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何参数。析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。

    1. #include <iostream>
    2. using namespace std;
    3. class Line
    4. {
    5. public:
    6. void setLength( double len );
    7. double getLength( void );
    8. Line(); // 这是构造函数声明
    9. ~Line(); // 这是析构函数声明
    10. private:
    11. double length;
    12. };
    13. // 成员函数定义,包括构造函数
    14. Line::Line(void)
    15. {
    16. cout << "Object is being created" << endl;
    17. }
    18. Line::~Line(void)
    19. {
    20. cout << "Object is being deleted" << endl;
    21. }
    22. void Line::setLength( double len )
    23. {
    24. length = len;
    25. }
    26. double Line::getLength( void )
    27. {
    28. return length;
    29. }
    30. // 程序的主函数
    31. int main( )
    32. {
    33. Line line;
    34. // 设置长度
    35. line.setLength(6.0);
    36. cout << "Length of line : " << line.getLength() <<endl;
    37. return 0;
    38. }