C++试题精选----类的封装和继承----NO.4

希望c++的入门者们闲暇之余,可以浏览思考,有什么问题欢迎留言或者私信。

类的封装和继承----NO.4

eg.声明一个Student类,在该类中包括一个数据成员:score(代表课程成绩)、两个静态数据成员:total_score(代表总分),count(代表学生总人数)。成员函数有:构造函数、析构函数、account(int)用于设置分数、静态成员函数sum()返回所有学生的总成绩、静态成员函数average()返回所有学生的平均成绩、print()用于打印当前学生对象的成绩等。在主程序中,输入某班同学的成绩,并调用上述函数打印全班同学的成绩、求出全班学生的成绩之和与平均分等。Student类的框架可参考:
class Student //声明Student类
{
public:
Student(int ); // 构造函数
~Student(); // 析构函数

void account(int);		// 设置分数
static int sum();		// 返回总成绩
static double average();	// 返回平均成绩

void print();			// 打印输出Student的相关信息  

private:
int score; // 分数
static int total_score; // 总分
static int count; // 总人数
}; // Student类声明结束
注意:静态成员和非静态成员的初始化方式的区别。

#include<iostream>
using namespace std;
class Student		//声明Student类
{	
public:
	Student( );	// 构造函数
	~Student();	// 析构函数
	
	void account(int);		// 设置分数
	static int sum();		// 返回总成绩
	static double average();	// 返回平均成绩
	
    void print();			// 打印输出Student的相关信息  
    void print1();

private:
   int score;				// 分数
   static int total_score;		// 总分
   static int count;			// 总人数
  // static double average;
}; // Student类声明结束
Student::Student( )
{
	score=0;
}
Student::~Student()
{
  
}
void Student::account(int Score)
{
	score=Score;
	total_score=score+total_score;
	count++;
}
int Student::sum()
{
	return total_score;
}
double Student::average()
{
	return total_score*1.0/count;
}
void Student::print1()
{
	cout<<"学生成绩 "<<score<<endl;
}
void Student::print()
{
	cout<<"总分为 "<<sum()<<endl;
	cout<<"平均分为 "<<average()<<endl; 
}
int Student::total_score=0;
int Student::count=0;
int main()
{
	Student shuzu[80];
	cout<<"输入学生人数: "<<endl;
	int Count;
	cin>>Count;
	int i=0;
	int a;
	cout<<"输入学生成绩"<<endl;
	for(i=0;i<Count;i++)
	{
		
		cin>>a;
		shuzu[i].account(a);
	}
	for(i=0;i<Count;i++)
	{
		shuzu[i].print1();
		
	}
	shuzu[0].print();
	return 0;
}

运行结果
在这里插入图片描述
有问题私聊博主或者在下面留言,如果有更好的解法也请留言,欢迎大家讨论,共同进步,一起学习。

C++是面向对象编程,我也想面向对象编程。”

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码的xiaolang

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值