函数中变量的生存期和作用域

C++中变量生存期与VB中大不相同,C++中非静态局部变量的生存周期仅限于其声明所在的块(即程序中对应的大括弧)中,在退出块时便会释放掉内存。
例:

class destruct
{
public:
    int mem;
    destruct()
    {
        mem = 0;
    }

    ~destruct()
    {
        mem++;
    }
};
void main()
{
    int * pa = NULL;
    {
        destruct odestruct;
    }
    if (true)
    {
        int a = 10;
        pa = &a;
    }
    for (int i = 0; i < 10; i++)
    {
        i++;
    }
    (*pa)++;
    cout<<*pa;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章