?? static.cpp
字號:
#include <iostream.h>
//靜態(tài)數(shù)據(jù)成員
/*
1.靜態(tài)成員函數(shù)不能在類的聲明中進行初始化,因為在類中不給它分配內(nèi)存空間,
它需要在類以外的其他地方(一般是在類的聲明之后和mian( )開始之前的某處)
提供定義和初始化。缺省情況下,靜態(tài)成員被初始化為零。
2.靜態(tài)數(shù)據(jù)成員和靜態(tài)變量一樣,是在編譯時創(chuàng)建并初始化的。它在該類的任何
對象被建立之前就存在,可以在程序內(nèi)部不依賴于任何對象被訪問。
3.支持靜態(tài)數(shù)據(jù)成員的原因是為了避免使用全局變量,避免破壞對類的封裝。
主要用于定義類的各個對象的公共數(shù)據(jù)。
*/
class CStudent {
static int Count;
int StudentNo;
public:
CStudent ( )
{
Count ++;
StudentNo = Count;
}
void Show ( )
{
cout << "Student" <<StudentNo << " ";
cout << "Count = "<<Count<< endl;
}
};
int CStudent::Count = 0; // 定義,并給靜態(tài)數(shù)據(jù)成員賦初值
void main( )
{
CStudent Student1;
CStudent Student2;
CStudent Student3;
CStudent Student4;
Student1.Show( );
Student2.Show( );
Student3.Show( );
Student4.Show( );
}
//靜態(tài)成員函數(shù)
/*
1.它可以在建立任何對象之前處理靜態(tài)數(shù)據(jù)成員,這是普通成員函數(shù)不能實現(xiàn)的功能。
2.在靜態(tài)成員函數(shù)中間不存在this指針,因為它不與特定對象相聯(lián)系。
*/
/*
class CStudent {
static int Count;
static float TotalAge;
int Age;
int StudentNo;
public:
CStudent (int age);
void Show ( );
static void ShowAveAge ( );
} ;
int CStudent::Count=0;
float CStudent::TotalAge=0;
CStudent :: CStudent (int age)
{
Count ++;
StudentNo = Count;
Age = age;
TotalAge = TotalAge + float ( Age );
}
void CStudent :: Show ( )
{
cout << "Student" << StudentNo ;
cout << "\'s age is" << Age << endl;
}
void CStudent :: ShowAveAge ( )
{
float ave_age;
ave_age = TotalAge / float(Count);
cout << "Number of Student is :" << Count << endl ;
cout << "Their ave_age is :" << ave_age << endl;
}
void main()
{
CStudent std1(22), std2(20), std3(21);
std1.Show( );
std2.Show( );
std3.Show( );
CStudent :: ShowAveAge ( );
}
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -