static定義全局變量
//Object.h
class Object
{
public:
static int number;
};
//Object.cpp
#include "Object.h"
int Object::number = 1;
//main.cpp
#include<stdio.h>
#include "Object.h"
int main()
{
Object::number = 2;
printf("%d\n",Object::number);
return 0;
}
- static變量的幾個要素
- 變量聲明放在類體(Object.h)大括號內(nèi),不能加初始值
- 變量定義放在類體之外
//Object.cpp
#include "Object.h"
int Object::number = 1;
- 在main函數(shù)中使用,和使用普通變量一樣,區(qū)別是要加上Object::前綴而已
int main()
{
Object::number = 2;
}
- static函數(shù)的幾個要素和變量要素相同
與普通成員的區(qū)別
- static變量不屬于這個類
class Object
{
public:
int a;
public:
static int b;
};
Object::a = 1;
Object::b = 2;
sizeof(Object)的值為4,因為它包含一個成員變量a,而b則不計入總大小
- static函數(shù)里沒有this指針,下列代碼是不正確的!
class Object
{
public:
int a;
public:
static void Set()
{
this->s = 1;
}
};
static語法的特點
- 受public/private限制
//Object.h
class Object
{
public:
void call();
private:
static void Test();
};
//Object.cpp
#include "Object.h"
void Object::Test()
{
printf("...");
}
void Object::Call()
{
Test(); //從內(nèi)部調(diào)用的時候,Object::可以忽略,加上也行
//Object::Test();
}
//main.cpp
#include "Object.h"
int main()
{
//Object::Test; 錯誤!由于是private,不允許被外部調(diào)用
Object obj;
Obj.Call(); //可以通過調(diào)用Call間接調(diào)用Test
}
- 可以自由訪問類的其他成員(普通的全局函數(shù)無法訪問類的私有成員)
//Object.h
class Object
{
private:
void DoSomething();
int x,y;
public:
static void Test(Object* obj);
};
//Object.cpp
//這里要賦給x,y值,由于Object沒有this指針,所以只能顯式地傳入一個對象
void Object::Test(Object* obj)
{
obj->x = 1;
obj->y = 2;
obj->DoSomething();
}
void Object::DoSomething
{
printf("...");
}
//main.cpp
Object obj;
Object::Test(&obj);