1、定义一个Student类,在该类定义中包括一个数据成员score(分数)、两个静态数据成员total(总分)和学生人数count;成员函数scoretotalcount(float s)用于设置分数、求总分和累计学生人数;静态成员函数sum()用于返回总分;静态成员函数average()用于求平均值。在main()函数中,输入某班同学的成绩,并调用上述函数求全班学生的总分和平均分。
2、声明Book与Ruler两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。
完整代码
student类:
#include<iostream>
using namespace std;
class Student
{
public:
void scoretotalcount();
static float sum();
static float average();
static float total;
static int count;
private:
float score;
};
void Student::scoretotalcount()
{
cout<<"请输入学生成绩:";
cin>>score;
total=total+score;
count++;
}
float Student::sum()
{
return(total);
}
float Student::average()
{
return(total/count);
}
float Student::total=0;
int Student::count=0;
int main()
{
Student stu[20];
int n;
while(1)
{
cout<<"请输入序号:"<<endl;
cout<<"1.添加学生成绩"<<endl;
cout<<"2.查询班级总分及平均分"<<endl;
cin>>n;
if(n==1)
{
stu[Student::count].scoretotalcount();
}
else if(n==2)
{
cout<<"总分:"<<Student::sum()<<endl;
cout<<"平均分:"<<Student::average()<<endl;
}
else
{
cout<<"格式有误,请重新输入!"<<endl;
}
cout<<endl;
}
return 0;
}
Book&Ruler:
#include<iostream>
using namespace std;
class Ruler;
class Book
{
public:
Book()
{
weight=55.2;
}
float totalWeight(Ruler &);
float weight;
};
class Ruler
{
public:
Ruler()
{
weight=43.6;
}
friend float Book::totalWeight(Ruler &);
float weight;
};
float Book::totalWeight(Ruler &rul)
{
return(weight+rul.weight);
}
int main()
{
Book boo;
Ruler rul;
cout<<"Book="<<boo.weight<<endl;
cout<<"Ruler="<<rul.weight<<endl;
cout<<"totalweight="<<boo.totalWeight(rul)<<endl<<endl;
}
仅作留档。