C++中的静态对象何时被销毁?
静态对象用关键字 static 声明。它们只初始化一次,存储在静态存储区域。静态对象只在程序终止时才会被销毁,即它们一直存在,直到程序终止。
下面给出了一个演示 C++ 中静态对象的程序。
示例
#include <iostream>
using namespace std;
class Base {
public :
int func() {
int a = 20;
cout << "The value of a : " << a;
}
};
int main() {
static Base b;
b.func();
return 0;
}输出
上述程序的输出如下。
The value of a : 20
现在让我们了解一下上面的程序。
Base 类中的函数 func() 声明了一个 int 变量 a,然后显示 a 的值。展示此功能的代码片段如下。
class Base {
public :
int func() {
int a = 20;
cout << "The value of a : " << a;
}
};在主函数中,创建了类 Base 的静态对象 b。然后调用函数 func()。由于对象 b 是静态的,因此仅在程序终止时才会销毁该对象。展示此功能的代码片段如下。
int main() {
static Base b;
b.func();
return 0;
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP