函數中變量的生存期和作用域

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;
}

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