成员函数中的静态变量如何在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;
}热门推荐
10 国庆简短幽默祝福语
11 年前幸福祝福语大全简短
12 祝女性生日祝福语简短
13 修祖屋祝福语简短
14 祝福语写给自己的简短
15 好朋友夫妻祝福语简短
16 夸赞老师祝福语搞笑简短
17 公司开年仪式祝福语简短
18 妈妈给宝贝祝福语简短