Details of static and variable data members in C++ programming

  • 2020-05-07 20:13:38
  • OfStack

static member
The
class can contain static member data and member functions. When a data member is declared "static," only one copy of the data is kept for all objects in the class.
A static data member is not part 1 of an object of the given class type. Therefore, the declaration of a static data member is not considered a definition. Declare the data member in the class scope, but execute the definition in the file scope. These static class members have external links. The following example illustrates this point:


// static_data_members.cpp
class BufferedOutput
{
public:
  // Return number of bytes written by any object of this class.
  short BytesWritten()
  {
   return bytecount;
  }

  // Reset the counter.
  static void ResetCount()
  {
   bytecount = 0;
  }

  // Static member declaration.
  static long bytecount;
};

// Define bytecount in file scope.
long BufferedOutput::bytecount;

int main()
{
}

In the previous code, the member bytecount was declared in class BufferedOutput, but it must be defined outside of the class declaration.
You can refer to static data members without referring to objects of class type. You can get the number of bytes written using the BufferedOutput object, as shown below:


long nBytes = BufferedOutput::bytecount;

For existing static members, the existence of all objects of a class type is not necessary. You can also use member selection (. And wok > ) operator accesses static members. Such as:


BufferedOutput Console;

long nBytes = Console.bytecount;

In the previous example, references to objects (Console) are not evaluated; The value returned is the value of the static object bytecount.
Static data members follow class member access rules, so only class member functions and friends are allowed to have private access to static data members.


variable data member
this keyword applies only to nonstatic and nonconstant data members of a class. If a data member is declared as mutable, it is legal to assign a value to this data member from the const member function.
grammar


mutable member-variable-declaration;

note
For example, the following code does not fail at compile time because m_accessCount has been declared as mutable and can therefore be modified by GetFlag, even though GetFlag is a constant member function.


// mutable.cpp
class X
{
public:
  bool GetFlag() const
  {
   m_accessCount++;
   return m_flag;
  }
private:
  bool m_flag;
  mutable int m_accessCount;
};

int main()
{
}


Related articles: