static关键字
那就是与 static 结合的成员变量和成员函数。类中的成员变量或成员函数一旦与 static 关键字相结合,则该成员变量或成员函数就是属于类的,而不是再是属于任何一个对象的,当然任何一个对象都可以共享该成员变量及成员函数。
#include<iostream>
using namespace std;
class test
{
public:
int ID; //成员变量
static int num; //静态成员变量
};
int test::num = 1;
int main()
{
test one;
test two;
test three;
cout<<test::num<<" "<<one.num<<" "<<two.num<<" "<<three.num<<endl;
test::num = 5;
cout<<test::num<<" "<<one.num<<" "<<two.num<<" "<<three.num<<endl;
one.num = 8;
cout<<test::num<<" "<<one.num<<" "<<two.num<<" "<<three.num<<endl;
two.num = 4;
cout<<test::num<<" "<<one.num<<" "<<two.num<<" "<<three.num<<endl;
three.num = 2;
cout<<test::num<<" "<<one.num<<" "<<two.num<<" "<<three.num<<endl;
return 0;
}

从程序运行结果可以看出,四种调用静态成员变量的方法,其值都是相等的,如果其中有任何一个修改该静态成员变量,所有其他的调用静态成员变量都会跟着一起改变。这就是静态成员变量的共享特性。
静态成员变量不属于任何对象,但是可以通过对象访问静态成员变量。静态成员变量属于类,因此可以通过类来调用静态成员变量。静态成员变量如果被设置为 private 或 protected 属性,则在类外同样无法访问,但定义该变量的时候却不受此限制,如例 2 所示,虽然静态成员变量 count 为 private 属性,但是它在类外定义的时候不受 private 限制。
静态成员函数
#include<iostream>
using namespace std;
class test
{
public:
static void add(int a);
};
void test::add(int a)
{
static int num = 0;
int count = 0;
num += a;
count += a;
cout<<num<<" "<<count<<endl;
}
int main()
{
test one,two,three;
one.add(5);
two.add(4);
three.add(11);
return 0;
}

本文详细介绍了C++中static关键字的应用,包括静态成员变量和静态成员函数。静态成员变量属于类,不归属于任何特定对象,可被所有对象共享。静态成员函数同样与对象无关,可以直接通过类名调用。示例代码展示了静态成员的使用和共享特性,以及如何通过对象或类来访问和修改它们。此外,还提到了静态成员变量的访问权限设定及其特性。
1140

被折叠的 条评论
为什么被折叠?



