static_critter.cpp

来自「the source of dev_c++ most of them for 」· C++ 代码 · 共 44 行

CPP
44
字号
//Static Critter
//Demonstrates static member variables and functions

#include <iostream>

using namespace std;

class Critter
{
public:
    static int s_Total;  //static member variable
                         //total number of Critter objects in existence
    
    Critter(int hunger = 0): m_Hunger(hunger)
    {
        cout << "A critter has been born!" << endl;
        ++s_Total;
    }

    static int GetTotal()  //static member function
    {
        return s_Total;
    }
    
private:
    int m_Hunger;
};

int Critter::s_Total = 0;  // initialize static member variable

int main()
{
    cout << "The total number of critters is: ";
    cout << Critter::s_Total << "\n\n";
     
    Critter crit1, crit2, crit3;
      
    cout << "\nThe total number of critters is: ";
    cout << Critter::GetTotal() << "\n";

    return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?