C++:构造函数、析构函数

构造函数用于初始化对象及相关操作。一般在创建类对象的时候构造函数会被自动调用
析构函数则用于销毁对象时完成相应的资源释放工作。一般在撤销类对象时会被自动调用

例:

#include <iostream>

using namespace std;

class Box {
    private:
        int height;

    public:
        Box(int b)
        {
            height = b;

            cout << "构造函数" << endl;
        }

        Box(const Box& A)
        {
            height = A.height;

            cout << "复制构造函数" << endl;
        }

        ~Box(void)
        {
             cout << "析构函数" << endl;
        }
};                                                                                                                                                                                    

void display(Box B)
{
    cout << "调用函数" << endl;
} 

int main(void)
{
    Box box(10);
    display(box);

    return 0;
} 
[john@localhost C++]$ g++ test.cc 
[john@localhost C++]$ ./a.out     
构造函数
复制构造函数
调用函数
析构函数
析构函数

猜你喜欢

转载自blog.csdn.net/keyue123/article/details/79136316