一、实验内容
1. 定义一个类Student记录学生计算机课程的成绩。要求使用静态成员变量或静态成员函数计算全班学生计算机课程的总成绩和平均成绩。编写一个测试程序来测试该类。
2. 设计一个类CTimeInfo,要求其满足下述要求。
(1) 要求有一个无参数的构造函数,其初始的小时和分钟分别为:0,0.
(2) 要求有一个带参数的构造函数,其参数分别对应小时和分钟。
(3) 要求用一个成员函数实现时间的设置。
(4) 要求用一个友员函数实现以12小时的方式输出时间。
(5) 要求用一个友员函数实现以24小时的方式输出时间。
二、实验目的
1. 掌握静态数据成员和静态成员函数的基本使用方法。
2. 理解友元与友元函数的作用,掌握其使用方法。
三、主要仪器设备及耗材
硬件:计算机一台
软件:VC++ 6.0,MSDN2003或者以上版本
四、实验步骤
1. 创建空白新工程,向新工程中添加空文件
2. 编写代码
3. 编译、调试并运行
五、实验数据及处理结果
试验内容(1)相关代码
Student.h文件代码:
#include<iostream>
using namespace std;
class student
{
public:
student(double m){ mark=m; sum+=mark; count++;}
static void Getim(){cout<<”sum=”<<sum<<”average=”<<sum/count<<endl;}
void display();
private:
double mark;
static double sum;
static int count;
};
void student::display()
{
cout<<”The student’mark is ”<< mark<<endl;
};
int student::count=0;
double student:: sum=0.0;
main函数代码:
#include<iostream>
#include”student.h”
using namespace std;
void main ()
{
student student1(90),student2(80),student3(70);
student2.Getim();
student::Getim();
}
试验内容(2)相关代码:
ctimeinfo.H文件代码:
#include<iostream>
using namespace std;
class CTimeInfo
{
public:
CTimeInfo(){minute=0;hour=0;}
CTimeInfo(int h,int m){hour=h;minute=m;}
void SetTime(int h ,int m);
friend void ShowTime12(CTimeInfo &a);
friend void ShowTime24(CTimeInfo &a);
private:
int hour;
int minute;
};
void ShowTime12(CTimeInfo &a)
{
cout<<a.hour%12<<”:”<<a.minute<<endl;
}
void ShowTime24(CTimeInfo &a)
{
cout<<a.hour<<”:”<<a.minute<<endl;
}
void CTimeInfo::SetTime(int h, int m)
{
hour=h;minute=m;
}
Main函数代码:
#include<iostream>
#include”ctimeinfo.h”
using namespace std;
void main()
{
CTimeInfo clock1,clock2(14,56);
ShowTime12(clock1);
ShowTime12(clock2);
clock1.SetTime(10,36);
clock2.SetTime(11,23);
ShowTime24(clock1);
ShowTime24(clock2);
}
六、思考讨论题或体会或对改进实验的建议