C++ 学生类

学生类——静态数据成员和静态成员函数

题目描述

定义一个类Student,要求使用静态数据成员或静态成员函数计算全班学生的《计算机导论》课程的总成绩和平均成绩。
静态数据成员:static int total;
静态成员函数:static void Average(){}

输入描述

学生姓名 课程成绩

输出描述

总成绩和平均成绩

输入样例
Zhang 82
Li 79
Wang 93
Liu 66
Xia 90
输出样例
410
82
程序代码
#include <iostream>
#include <cstring>

using namespace std;

class Student {
	private:
		double m_score; // 学生分数
		char m_name[64];

		// 统计学生个数的静态成员变量
		static int m_count;

		// 统计学生总分数的静态成员变量
		static double sum_score;

	public:
		Student() {
		}
		
		Student(char *name ,double score) {
			// 创建一个学生
			m_score = score;

			m_count++; // 对创建的学生对象的人数进行累加 
			sum_score += score;  // 对创建的学生对象的分数进行累加 
			
			strcpy(m_name, name);
		}

		static double Average() {   // 提供一个访问平均分的静态方法 
			return sum_score / m_count;
		}
		
		static double getSumScore() {   // 提供一个访问总分的静态方法 
			return sum_score;
		}
				
		~Student() {
			m_count--;   // 每析构一个对象,数量减去一 
			sum_score -= m_score; // 析构一个对象,减去对象对应的学生分数 
			
		}
};


int Student::m_count = 0;  // 对静态变量进行初始化 

double Student::sum_score = 0.0; // 对静态变量进行初始化 

int main(){
	
	Student *s1 = new Student("Zhang", 82);
	Student *s2 = new Student("Li", 79);
	Student *s3 = new Student("Wang", 93);
	Student *s4 = new Student("Liu", 66);
	Student *s5 = new Student("Xia", 90);
	
	cout << Student::getSumScore() << endl;
	cout << Student::Average() << endl;
	
	delete s5;  
	delete s4;
	delete s3;
	delete s2;
	delete s1;

	return 0;
}

学生成绩高低——友元函数

题目描述

在第一题的基础上,设计一个友元函数,比较某两个学生成绩的高低。

输入描述

学生姓名和分数

输出描述

分数高低的结果(>或<或==)

输入样例
zhang 92
li 89
输出样例
>
程序代码
#include <iostream>
#include <string.h>

using namespace std;
 
class Student{
	private:
	    int m_score;   // 分数 
	    char * m_name; // 姓名 
	    
	public:
	    Student(const char * n, int score);//构造函数
	    friend char Compare(const Student stu1, const Student stu2);
	    ~Student();    
	    Student();
};
 
Student::Student(const char * name, int score){//构造函数
    int len = strlen(name);
    m_name = new char[len+1];
    strcpy(m_name, name);
    
    m_score = score;
}

Student::~Student() {			
		if (m_name != NULL) {
			m_name = NULL;
		}
	}
 
char Compare(const Student stu1, const Student stu2){  // 比较某两个学生成绩的高低 
    if(stu1.m_score > stu2.m_score) {
    	return('>');
	} else if (stu1.m_score < stu2.m_score){
		return('<');
	} else {
		return('=');
	} 
}

int main(){
	
    char name[64];  
    int score;
    
    cin >> name >> score;
    Student *stu1 = new Student(name, score);  // 创建对象 
    
    cin >> name >> score;
    Student *stu2 = new Student(name, score);  // 创建对象 
    
    cout << Compare(*stu1, *stu2) << endl;  // 输出结果 
    
    delete stu1;
    delete stu2;
    
    return 0;
}
  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值