Static 静态成员函数 和 static成员的访问 【C++ static】

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值