C++ 中类成员函数中的静态变量如何工作?
成员函数中的静态变量使用关键字 static 声明。静态变量的空间只分配一次,并且在整个程序中使用它。此外,整个程序中只有这些静态变量的一个副本。
一个演示 C++ 中成员函数中静态变量的程序如下所示。
示例
#include <iostream>
using namespace std;
class Base {
public :
int func() {
static int a;
static int b = 12;
cout << "The default value of static variable a is: " << a;
cout << "\nThe value of static variable b is: " << b;
}
};
int main() {
Base b;
b.func();
return 0;
}输出
上述程序的输出如下。
The default value of static variable a is: 0 The value of static variable b is: 12
现在让我们理解一下上述程序。
类 Base 中的成员函数 func() 包含两个静态变量 a 和 b。a 的默认值为 0,b 的值为 12。然后将这些值显示出来。显示它的代码片段如下。
class Base {
public :
int func() {
static int a;
static int b = 12;
cout << "The default value of static variable a is: " << a;
cout << "\nThe value of static variable b is: " << b;
}
};在 main() 函数中,创建了类 Base 的对象 b。然后调用函数 func()。显示它的代码片段如下。
int main() {
Base b;
b.func();
return 0;
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP