#include
#include
using namespace std;
class Stud
{private:
int no;
char name;
float deg;
public:
static float sum;
static int num;
static float avg();
static void disp();
};
float Stud::sum=0.0;
int Stud::num=0;
Stud::Stud(int m,char n,float d)
{no=m;
name=n;
deg=d;
sum+=deg;
}
float Stud::avg()
{return sum/num;}
void Stud::disp()
{cout<<"學號:"<<no<<endl;
cout<<"姓名:"<<name<<endl;
cout<<"成績:"<<deg<<endl;
cout<<"平均分:"<<avg()<<endl;
}
int main()
{
Stud s1(101,"Xiaoming",84),s2(102,"Xiaohong",94),s3(103,"Xiaofang",87);
s1.avg();
s1.disp();
s2.avg();
s2.disp();
s3.avg();
s3.disp();
return 0;
}
構造函數重載需要在類中聲明才能使用,另外一個是非靜態成員變量不能直接在靜態成員函數中使用,可以采用類指針(模擬類似this指針)解決。
#include <iostream>
using namespace std;
class Stud
{
private:
int no;
char* name;
float deg;
public:
Stud(int m, char* n, float d);
static float sum;
static int num;
static float avg(Stud* stud);
static void disp(Stud* stud);
};
float Stud::sum = 0.0;
int Stud::num = 3;
Stud::Stud(int m, char* n, float d)
{
no=m;
name=n;
deg=d;
sum+=deg;
}
float Stud::avg(Stud* stud)
{
return stud->sum/stud->num;
}
void Stud::disp(Stud* stud)
{
cout<<"學號:"<<stud->no<<endl;
cout<<"姓名:"<<stud->name<<endl;
cout<<"成績:"<<stud->deg<<endl;
cout<<"平均分:"<<stud->avg(stud)<<endl;
}
int main()
{
Stud s1(101,"Xiaoming",84),s2(102,"Xiaohong",94),s3(103,"Xiaofang",87);
s1.avg(&s1);
s1.disp(&s1);
s2.avg(&s2);
s2.disp(&s2);
s3.avg(&s3);
s3.disp(&s3);
return 0;
}