C++/Language/Static

Материал из C\C++ эксперт
Версия от 10:28, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A shared resource example.

#include <iostream>
#include <cstring>
using namespace std;
class output {
  static char sharedResource[255]; // this is the shared resource
  static int inuse;        // buffer available if 0; in use otherwise
  static int oindex;       // index of sharedResource
  char str[80];
  int i;                   // index of next char in str
  int who;                 // identifies the object, must be > 0
public:
  output(int w, char *s) { 
     strcpy(str, s); 
     i = 0; 
     who = w; 
  }
  int putbuf() 
  {
    if(!str[ i ]) {         // done outputting
      inuse = 0;            // release buffer
      return 0;             // signal termination
    }
    if(!inuse)              // get buffer
        inuse = who; 
    if(inuse != who)        // in use by someone else
        return -1; 
    if(str[ i ]) {          // still chars to output
      sharedResource[oindex] = str[ i ];
      i++; oindex++;
      sharedResource[oindex] = "\0";// always keep null-terminated
      return 1;
    }
    return 0;
  }
  void show() { 
     cout << sharedResource << "\n"; 
  }
};
char output::sharedResource[255];   // this is the shared resource
int output::inuse = 0;      // buffer available if 0; in use otherwise
int output::oindex = 0;     // index of sharedResource
int main()
{
  output object1(1, "This is a test"), object2(2, " of statics");
  while(object1.putbuf() | object2.putbuf()) ; // output chars
  object1.show();
  return 0;
}


A static member variable example.

#include <iostream>
using namespace std;
class myclass {
  static int i;
public:
  void setInt(int n) { 
     i = n; 
  }
  int getInt() { 
     return i; 
  }
};

int myclass::i;           // Definition of myclass::i. i is still private to myclass.
int main()
{
  myclass object1, object2;
  object1.setInt(10); 
  cout << "object1.i: " << object1.getInt() << "\n"; // displays 10
  cout << "object2.i: " << object2.getInt() << "\n"; // also displays 10 
  return 0;
}


Init static data before object creation

#include <iostream>
using namespace std;
class StaticMemberClass {
  static int i;
public:
  static void init(int x) {
     i = x;
  }
  void show() {
     cout << i;
  }
};
int StaticMemberClass::i; // define i
int main()
{
  
  StaticMemberClass::init(100);
  StaticMemberClass x;
  x.show(); 
  return 0;
}


Static function and static variable

#include <iostream>
using namespace std;
class MyClass {
  static int i;
public:
  static void init(int x) {
     i = x;
  }
  void show() {
     cout << i;
  }
};
int MyClass::i;
int main()
{
  // init static data before object creation
  MyClass::init(30);
  MyClass x;
  x.show();
  return 0;
}


Static function variable

#include <iostream>
using namespace std;
void printMessage(void);  
int main ()
{
   char choice;
   do {
      cout << "Enter Q to quit, any other character to continue: ";
      cin >> choice;
      if (choice == "Q")
         cout << "Input stopped";
      else
         printMessage(); 
      } while (choice != "Q");
   return 0;
}
void printMessage (void)
{
   static int times = 0;
   times++;
   cout << "This function called " << times << " times\n";
}


Static Member Functions: its strictions

//A static member function does not have a this pointer. 
//cannot be a static and a non-static version of the same function. 
//A static member function may not be virtual. 
//static functions cannot be declared as const or volatile.
#include <iostream>
using namespace std;
class MyClass {
  static int resource;
public:
  static int getResource();
  void freeResource() { 
     resource = 0; 
  }
};
int MyClass::resource;   // define resource
int MyClass::getResource()
{
  if(resource) return 0; // resource already in use
  else {
    resource = 1;
    return 1;            // resource allocated to this object
  }
}
int main()
{
  MyClass myObject1, myObject2;
  if(MyClass::getResource()) 
     cout << "myObject1 has resource\n";
  if(!MyClass::getResource()) 
     cout << "myObject2 denied resource\n";
  myObject1.freeResource();
  
  if(myObject2.getResource()) 
    cout << "myObject2 can now use resource\n";
  return 0;
}


Static member functions: "preinitialize" private static data

#include <iostream>
using namespace std;
class static_type {
  static int i;
public:
  static void init(int x) {
     i = x;
  }
  void show() {
     cout << i;
  }
};
int static_type::i;
int main()
{
  
  static_type::init(100);   // init static data before object creation
  static_type x;
  x.show(); 
  return 0;
}


Usage and effect of a static data member

#include <iostream>
using namespace std;
class shared {
  static int a;
  int b;
public:
  void set(int i, int j) {
    a=i; 
    
    b=j;
  }
  void show();
} ;
int shared::a;
void shared::show()
{
  cout << "This is static a: " << a;
  cout << "\nThis is non-static b: " << b;
  cout << "\n";
}
int main()
{
  shared x, y;
  x.set(1, 1); 
  x.show();
  y.set(2, 2); 
  y.show();
  x.show(); 
  return 0;
}


Use a static member variable independent of any object.

#include <iostream>
using namespace std;
class myclass {
public:
  static int i;
  void setInt(int n) { 
     i = n; 
  }
  int getInt() { 
     return i; 
  }
};
int myclass::i;
int main()
{
  myclass object1, object2;
  
  myclass::i = 100;                      // set i directly,  no object is referenced.
  cout << "object1.i: " << object1.getInt() << "\n"; // displays 100
  cout << "object2.i: " << object2.getInt() << "\n"; // also displays 100
  return 0;
}