static修飾,例如:
class Student{
public:
Student(char *name, int age, float score);
void show();
public:
static int m_total; //靜態成員變量
private:
char *m_name;
int m_age;
float m_score;
};
這段代碼聲明了一個靜態成員變量 m_total,用來統計學生的人數。type class::name = value;
type 是變量的類型,class 是類名,name 是變量名,value 是初始值。將上面的 m_total 初始化:int Student::m_total = 0;
靜態成員變量在初始化時不能再加 static,但必須要有數據類型。被 private、protected、public 修飾的靜態成員變量都可以用這種方式初始化。
//通過類類訪問 static 成員變量
Student::m_total = 10;
//通過對象來訪問 static 成員變量
Student stu("小明", 15, 92.5f);
stu.m_total = 20;
//通過對象指針來訪問 static 成員變量
Student *pstu = new Student("李華", 16, 96);
pstu -> m_total = 20;
這三種方式是等效的。
#include <iostream>
using namespace std;
class Student{
public:
Student(char *name, int age, float score);
void show();
private:
static int m_total; //靜態成員變量
private:
char *m_name;
int m_age;
float m_score;
};
//初始化靜態成員變量
int Student::m_total = 0;
Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){
m_total++; //操作靜態成員變量
}
void Student::show(){
cout<<m_name<<"的年齡是"<<m_age<<",成績是"<<m_score<<"(當前共有"<<m_total<<"名學生)"<<endl;
}
int main(){
//創建匿名對象
(new Student("小明", 15, 90)) -> show();
(new Student("李磊", 16, 80)) -> show();
(new Student("張華", 16, 99)) -> show();
(new Student("王康", 14, 60)) -> show();
return 0;
}
運行結果:int Student::m_total = 10;
初始化時可以賦初值,也可以不賦值。如果不賦值,那麼會被默認初始化為 0。全局數據區的變量都有默認的初始值 0,而動態數據區(堆區、棧區)變量的默認值是不確定的,一般認為是垃圾值。