c++ 静态成员
就像變量一樣,對象也在聲明為static時具有范圍,直到程序的生命周期。
考慮以下程序,其中對象是非靜態(tài)的。
動態(tài)對象
#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 mainProcess finished with exit code 0靜態(tài)對象
#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 DestructorProcess finished with exit code 0總結(jié)
- 上一篇: c++ static 静态变量初始化
- 下一篇: c++ 交换变量实践