C++类中static修饰的函数的使用

//在C++中应该养成习惯:只用静态成员函数引用静态成员数据,而不引用非静态成员数据

#include <iostream>
using namespace std;
class st_info   //定义学生信息类
{
    private:
        string name;
        int num;
        float score;
        static float sum; // 静态数据成员
        static int count; // 静态数据成员
       
    public:
        st_info(string, int, float);//构造函数
        void total();
        static float average();
       
};

st_info:: st_info(string n, int no, float s)//定义构造函数
{
    name = n, num = no, score = s;
}

void st_info:: total()//定义非静态函数
{
    sum += score;
    count++;
}

float st_info :: average()//定义静态函数
{
    return sum / count;
}

float st_info:: sum = 0;
int st_info:: count = 0;

int main()
{
    st_info studt[3] =  //定义三个成员,并分别初始化
    {
        st_info("zhangsan", 18, 70),
        st_info("lisi", 18, 80),
        st_info("wanger", 18, 90),
    };

    int i;// n  = st_info::count;
    for(i = 0; i < 3; i++)
    {
        studt[i].total();
    }

    float average = st_info:: average();

    cout << "average = " << average << endl;

 
    return 0;
}

 

 

原文地址:https://www.cnblogs.com/xuyh/p/3200910.html