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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值