1)static成员变量属于类,不属于某个具体的对象,即使创建多个对象,也只为static成员变量分配一个内存
所有对象都是这个内存里的statiic变量,如果对其做出修改也会影响到其他对象的使用
2)static成员变量必须在类外进行初始化
形如 type class ::name = value; int Parent ::count = 0;
class Parent
{
public:
int age;
int score;
static int count;
Parent(int age, int score);
void Show()
{
cout << age << " " << score << endl;
cout << count << endl;
}
};
int Parent :: count = 0; ///在类外初始化
Parent ::Parent(int age, int score)
{
this->age = age;
this->score = score;
count++;
}
int main()
{
Parent P(2, 3);
P.Show();
Parent p(3, 4);
p.Show();
while(1);
return 0;
}
3)static成员变量不占用对象内存,是在对象之外(全局数据区)开辟一块内存,即使不创建对象也不能访问。
4)static成员变量不随对象的创建而创建,不随对象的销毁而销毁,在程序结束时在销毁;普通成员变量随对象创建,随对象销毁
class Parent
{
public:
int age;
int score;
static int count;
Parent(int age, int score);
void Show()
{
cout << age << " " << score << endl;
cout << count << endl;
}
};
int Parent :: count = 0;
Parent ::Parent(int age, int score)
{
this->age = age;
this->score = score;
count++;
}
int main()
{
cout << Parent :: count << endl; //未创建对象,一样访问,打印出来值为0
while(1);
return 0;
}