zoukankan      html  css  js  c++  java
  • 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;
    }

     

     

  • 相关阅读:
    luogu P2685 [USACO07OPEN]抓牛Catch That Cow
    codevs 2021 中庸之道
    1018. 锤子剪刀布 (20)
    1017. A除以B (20)
    1016. 部分A+B (15)
    1013. 数素数 (20)
    1011. A+B和C (15)
    《C语言程序设计(第四版)》阅读心得(三)
    《C语言程序设计(第四版)》阅读心得(二)
    1008. 数组元素循环右移问题 (20)
  • 原文地址:https://www.cnblogs.com/xuyh/p/3200910.html
Copyright © 2011-2022 走看看