#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
class Student {
public :
Student(char *name1, char *stu_no1, float score1);
~Student();
void show();
static void show_count_sum_avg(); // 输出学生人数和平均成绩
private :
char *name; // 成员变量中有指针
char *stu_no;
float score;
static int count; // 静态数据成员, 用于统计学生人数
static float sum; // 静态数据成员, 用于统计累加成绩
static float avg; // static数据成员的声明, 用于统计平均成绩
};
Student::Student(char *name1, char *stu_no1, float score1) { // 定义构造函数
name = new char[strlen(name1) + 1];
strcpy(name, name1);
stu_no = new char[strlen(stu_no1) + 1];
strcpy(stu_no, stu_no1);
score = score1;
++count;
sum += score;
avg = sum / count;
}
Student::~Student() {
delete []name;
delete []stu_no;
--count;
sum = sum - score;
}
void Student::show() {
cout << "姓名 : " << name << endl;
cout << "学号 : " << stu_no << endl;
cout << "成绩 : " << score << endl;
cout << "哈哈 " << count << endl; // 非static成员函数可以访问 static 成员,貌似反过来是不行的!因为没办法嘛!
}
void Student::show_count_sum_avg() {
cout << "学生人数 : " << count << endl;
cout << "平均成绩 : " << avg << endl;
cout << endl;
}
int Student::count = 0; // static 数据成员的定义
float Student::sum = 0.0;
float Student::avg = 0.0;
int main() {
Student stu1("Liming", "01040981", 90);
stu1.show();
Student::show_count_sum_avg(); // 类调用
Student stu2("GaoShang", "01040982", 110);
stu2.show();
stu2.show_count_sum_avg(); // 对象调用!
system("pause");
return 0;
}
Static 静态成员函数 和 static成员的访问 【C++ static】
最新推荐文章于 2024-08-14 17:18:35 发布