C++学习笔记-2-构造函数和析构函数

问题2. 什么时候执行构造函数和析构函数  22:59:40 2015-07-22

做了一个实验:

#include <iostream>
class Object{
public:
    Object(){
        printf("Create Object\n");
    };
    ~Object(){
        printf("Delete Object\n");
    }
};
void runObject(){
    Object obj;
    printf("runObject end\n");
}
int main(){
//    Object *obj=new Object();
//    delete obj;
    runObject();
    printf("end\n");
    return 0;
}

输出为:

Create Object
runObject end
Delete Object
end

在void  runObject()中加一个{}

#include <iostream>
class Object{
public:
    Object(){
        printf("Create Object\n");
    };
    ~Object(){
        printf("Delete Object\n");
    }
};
void runObject(){
    {
        Object obj;
    }
    printf("runObject end\n");
}
int main(){
//    Object *obj=new Object();
//    delete obj;
    runObject();
    printf("end\n");
    return 0;
}

输出为:

Create Object
Delete Object
runObject end
end

 

posted @ 2015-07-22 23:04  hopskin1  阅读(145)  评论(0编辑  收藏  举报