成员函数中的静态变量使用关键字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
现在让我们了解上面的程序。
func()Base类中的成员函数包含两个静态变量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;
}