C++之static

static做为关键字,在C++语言中运用在类中,代表着这个属性或者方法属于这个类
如果生成的对象修改了这个成员,那么其他对象共享修改后的值

定义和初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ABC
{
public:
int getC()
{
return c;
}
void setC(int _c)
{
c = _c;
}
static void getMem()
{
cout << c << endl;
}
protected:
private:
int a;
int b;
static int c;
};
int ABC::c = 0;

若有对象修改了static修饰的变量,那么其他对象也是得到修改过后的值
static修饰的变量,属于类,所有的对象都能共享用
static修饰的方法,不能使用非静态的成员,原因是不知道这个成员属于哪个对象

调用方法

由于static是属于类的,故可以用类直接调用

1
ABC::getMem();

同时也可以直接用对象调用

1
2
ABC abc;
abc.getMem();

Donate comment here