构造函数和析构函数的调用

构造函数和析构函数的调用
#include <iostream>
using namespace std;

class Reader{
public:
    Reader()
    {
        xCoordinate = NULL;
        xCoordinate = (int*)malloc(sizeof(int)*100);
        cout<<"reader default construction"<<endl;
    }
    ~Reader()
    {
        cout<<"reader destruction!"<<endl;
        if(xCoordinate)
            free(xCoordinate);
    }
    int *xCoordinate;
};

class Reader2{
public:
    Reader2()
    {
        cout<<"reader2 constructor!"<<endl;
    }
    ~Reader2()
    {
        cout<<"reader2 destructor"<<endl;
    }
};
class Converter{
public:
    Converter()
    {
        reader2 = NULL;
        reader = new Reader();
        cout<<"converter constructor invoked!"<<endl;
    }
    ~Converter()
    {
        cout<<"converter destruction invoked!"<<endl;
        if(reader)
            delete reader;
        //if(reader2)
        //    delete reader2;
    }
    void DoHandle()
    {
        //reader2的析构函数和构造函数在一层才和谐
        reader2 = new Reader2();
        delete reader2;
        reader2 = NULL;
    }
    Reader *reader;
    Reader2 *reader2;
};


int main()
{
    //调用Converter的构造
    //在超出该变量的作用域,就自动析构了,比如这里就是函数的 } 
    Converter converter;

    Converter *pConverter; //不调用构造函数
    pConverter = new Converter(); //调用构造函数

    Converter *p2Converter; //指针的声明
    p2Converter = new Converter(); //调用构造函数
    delete p2Converter; //调用析构函数

    Converter *p3Converter = new Converter();
    p3Converter->DoHandle();
    delete p3Converter;

    //不调用Reader2的构造和析构
    Converter *p3Converter = new Converter();
    delete p3Converter;

    return 0;
}
构造函数和析构函数的调用

构造函数和析构函数的调用

上一篇:【转】C语言 字符数组与字符串


下一篇:POJ 3261 Milk Patterns (求可重叠的k次最长重复子串)+后缀数组模板