zoukankan      html  css  js  c++  java
  • C++(三十一) — 静态成员变量、静态成员函数

    1、静态成员变量

      类的静态成员变量是,由该类的所以对象共同维护和使用的数据成员,每个类只有一个副本,是类数据成员的一种特例。采用 static 关键字声明。

      目的:实现同一类中不同对象之间的数据共享。不包含 this 指针,因为是属于整个类的。

      初始化必须在类外进行,类内声明,类外初始化。可以通过类名,或对象名访问。

    class student
    {
    public:
        student(char* pName = "no name");  // 此处设置了默认参数
        ~student();
        void printS()
        {
            cout << "The number of student is " << count << endl;
        }
    private:
        static int count;  // 类内声明,类外初始化
        string name;
    };
    
    student::student(char* pName)
    {
        cout << "creat one student" << endl;
        name = pName;
        count++;  //自加1
    }
    student::~student()
    {
        cout << "destruct one student" << endl;
        count--;  // 自减1
        cout << "The number of student is " << count << endl;
    }
    // 声明静态成员函数
    int student::count = 0;
    
    void main()
    {
        student s1;
        s1.printS();
        student s2;
        s2.printS();
    
        system("pause");
    }

      每次定义一个学生类,静态成员变量 count 就自加1。

    2、静态成员函数

      静态成员函数只能调用静态成员变量,不能调用一般的变量(因为一般变量属于对象,对象不同就不知道调用哪个)。

      可以通过类名、或者对象名进行调用,它是属于一个类的函数。非静态的公有成员函数,只能通过对象、对象指针调用。

    static void printS()
        {
            cout << "The number of student is " << count << endl;
        }
  • 相关阅读:
    To the Virgins, to Make Much of Time
    瓦尔登湖
    贪心算法
    R语言实战 —— 常见问题解决方法
    R语言实战(四)—— 基本数据管理
    R语言实战(三)——模拟随机游走数据
    Vim——回顾整理
    Clion下载安装使用教程(Win+MinGW)
    【ACM】孪生素数问题
    【ACM】一种排序
  • 原文地址:https://www.cnblogs.com/eilearn/p/10217309.html
Copyright © 2011-2022 走看看