在C语言中曾经学习过静态变量, 其定义为经过static修饰过的变量, 其有着与整个源程序相同的生命周期, 其作用域与自动变量相同, 又分为静态全局变量和静态局部变量.
静态成员,指的是在C++类中声明成员时,可以加上static关键字,这样声明的成员叫静态成员,静态成员分为静态数据成员和静态函数成员两种
class Node
{
public:
static int id; //静态数据成员定义
};
int Node::id = 10; //静态数据成员类外初始化
类中静态数据成员, 所有对象共享该数据, 只存在一份内存
// 例
// 1.非静态成员
#include<iostream>
using namespace std;
class CA {
public:
int x;
};
int main()
{
CA a1, a2;
a1.x = 10;
a2.x = 15;
printf("a1:%d --> a2:%d", a1, a2); // a1:10 --> a2:15
}
// 2.静态成员
#include<iostream>
using namespace std;
class CB {
public:
static int x;
};
int CB::x = 10;
int main()
{
CB b1, b2;
printf("b1:%d-->b2:%d\n", b1.x, b2.x); // b1:10-->b2:10
b1.x = 15;
printf("b1:%d-->b2:%d\n", b1.x, b2.x); // b1:15-->b2:15
b2.x = 30;
printf("b1:%d-->b2:%d\n", b1.x, b2.x); // b1:30-->b2:30
}
// 发现当b1.x和b2.x的内存是相同的, 当b1.x改变,b2.x也随之改变
类中静态数据成员, 所有必须要在类外初始化, 它并不属于对象, 属于类
#include<iostream>
using namespace std;
class CB {
public:
static int x;
};
int CB::x = 10;
int main()
{
CB::x = 100;
cout << CB::x; //结果: 100
}
类中静态数据成员, 可以在类中被重新赋值, 也可以被普通函数访问, 如果该函数是公有属性
#include
using namespace std;
class CB {
public:
static void fun() {} // 在类中定义
static void fun1(); // 类中声明
};
void CB::fun1() {} // 在类外定义
类静态函数成员也不属于对象, 属于类. 在该函数中不能操作类中的普通数据成员和普通函数成员
#include<iostream>
using namespace std;
class CB {
public:
static void fun() {} // 在类中定义
static void fun1(); // 类中声明
void fun2() {}
int x;
};
void CB::fun1() {
x = 10; // 报错!! 静态成员函数不能操作普通数据成员和普通函数成员
fun2(); // 报错!! 静态成员函数不能操作普通数据成员和普通函数成员
}
访问和静态数据成员一致
#include<iostream>
using namespace std;
class CB {
public:
static void fun();
};
void CB::fun() {}
int main()
{
CB b1, b2;
b1.fun();
b2.fun();
return 0;
}
静态函数成员中, 不能访问类的普通成员, 静态函数成员, 在有没有对象的情况下都可以用, 可以在静态的函数中使用局部变量
#include<iostream>
using namespace std;
class CB {
public:
static void fun();
};
void CB::fun() {}
int main()
{
CB::fun();
return 0;
}