?? 例9.11.txt
字號:
例9.11 靜態成員函數的應用。
#include <iostream>
using namespace std;
class Student //定義Student類
{public:
Student(int n,int a,float s):num(n),age(a),score(s){ } //定義構造函數
void total( );
static float average( ); //聲明靜態成員函數
private:
int num;
int age;
float score;
static float sum; //靜態數據成員
static int count; //靜態數據成員
};
void Student∷total( ) //定義非靜態成員函數
{sum+=score; //累加總分
count++; //累計已統計的人數
}
float Student∷average( ) //定義靜態成員函數
{return(sum/count);
}
float Student∷sum=0; //對靜態數據成員初始化
int Student∷count=0; //對靜態數據成員初始化
int main( )
{Student stud[3]={ //定義對象數組并初始化
Student(1001,18,70),
Student(1002,19,78),
Student(1005,20,98)
};
int n;
cout<<″please input the number of students:″;
cin>>n; //輸入需要求前面多少名學生的平均成績
for(int i=0;i<n;i++) //調用3次total函數
stud[i].total( );
cout<<″the average score of ″<<n<<″ students is ″<<Student∷average( )<<endl;
//調用靜態成員函數
return 0;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -