Caminhoneiro

Class functions statics examples

Apr 20th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include "stdafx.h"
  2. //Demonstrate
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. class Critter //Class definition > defines a new type, Critter
  9. {
  10.     private:
  11.         int m_Rage;
  12.  
  13.     public :
  14.         int m_Hunger; // data member
  15.         Critter(int hunger = 0, int rage = 0); //Constructor prototype
  16.  
  17.         int GetRage() const;
  18.         void SetRage(int rage);
  19.  
  20.         void Greet(); //member function prototype
  21.  
  22.         static int s_Total; //Static member variable declaration // total numbers of Critters obj in existence
  23.  
  24.         static int GetTotal(); //Static function member prototype
  25.  
  26. };
  27.  
  28.  
  29. int Critter::s_Total = 0; //Static member variable initialization
  30.  
  31. Critter::Critter(int hunger, int rage): //Constructor definition
  32.     m_Rage(rage)
  33. {
  34.     cout << "New critter has been born" << endl;
  35.     m_Hunger = hunger;
  36.     ++s_Total;
  37. }
  38.  
  39. int Critter::GetTotal() {       //Static member function defition
  40.     return s_Total;
  41. }
  42.  
  43.  
  44. void Critter::Greet() //Member function definition
  45. {
  46.     cout << "Hi. I'm a critter. My hunger level is " << m_Hunger << ".\n";
  47. }
  48.  
  49. int Critter::GetRage() const
  50. {
  51.     return m_Rage;
  52. }
  53.  
  54. void Critter::SetRage(int rage) {
  55.     if (rage < 0)
  56.     {
  57.         cout << "You can set the critters rage to a negative n. \n\n";
  58.     }
  59.     else
  60.     {
  61.         m_Rage = rage;
  62.     }
  63. }
  64.  
  65.  
  66. int main() {
  67.     Critter crit1(4);
  68.     Critter crit2;
  69.  
  70.     //crit1.m_Hunger = 9;
  71.     cout << "crit1's hunger lvl is: " << crit1.m_Hunger << ".\n";
  72.  
  73.     crit2.m_Hunger = 3;
  74.     cout << "crit2's hunger lvl is: " << crit2.m_Hunger << ".\n\n";
  75.  
  76.     crit1.Greet();
  77.     crit2.Greet();
  78.  
  79.     crit1.SetRage(6);
  80.  
  81.     cout << "Get the rage: " << crit1.GetRage() << ".\n\n";
  82.  
  83.     cout << "\n The number of Critters is: " << Critter::GetTotal() << "\n";
  84.     //I can get access by any object of the class Ex:. cout << crit1.GetTotal();
  85.  
  86.  
  87.  
  88.  
  89.  
  90.     return 0;
  91.  
  92. }
Add Comment
Please, Sign In to add comment