成员函数中的静态变量如何在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
现在让我们了解上面的程序。
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;
}热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便