c++ 静态成员

就像变量一样,对象也在声明为static时具有范围,直到程序的生命周期。
考虑以下程序,其中对象是非静态的。

动态对象
#include<iostream>
using namespace std;

class Apple
{
    int i;
public:
    Apple()
    {
        i = 0;
        cout << "Inside Constructor\n";
    }
    ~Apple()
    {
        cout << "Inside Destructor\n";
    }
};

int main()
{
    int x = 0;
    if (x==0)
    {
        Apple obj;
    }
    cout << "End of main\n";
}
/home/ledi/.CLion2016.2/system/cmake/generated/c3-cf26d9f6/cf26d9f6/Debug/c3
Inside Constructor
Inside Destructor
End of main

Process finished with exit code 0
静态对象
#include<iostream> 
using namespace std; 

class Apple 
{ 
    int i; 
    public: 
        Apple() 
        { 
            i = 0; 
            cout << "Inside Constructor\n"; 
        } 
        ~Apple() 
        { 
            cout << "Inside Destructor\n"; 
        } 
}; 

int main() 
{ 
    int x = 0; 
    if (x==0) 
    { 
        static Apple obj; 
    } 
    cout << "End of main\n"; 
} 
/home/ledi/.CLion2016.2/system/cmake/generated/c3-cf26d9f6/cf26d9f6/Debug/c3
Inside Constructor
End of main
Inside Destructor

Process finished with exit code 0

posted @ 2022-08-19 22:48  luoganttcc  阅读(4)  评论(0)    收藏  举报