Implementation of C++ static data members
- 2020-06-12 10:07:32
- OfStack
Static data members are data members declared in a class with the keyword static. In C++, static members are generally used instead of C global variables to achieve data sharing. The global variables of C and C++ are limited by 1. They can be modified arbitrarily and may easily conflict with other variable names. Therefore, in C++, 1 does not use global variables.
Static data members must be initialized outside of the class, and static data members can also reference, but not private data parts.
Here's an example:
#include <iostream>
#include <cstring>
using namespace std ;
class Student
{
private :
// Static member variable
static int age ;
static float score ;
string name ;
public :
static int x , y ;
// The constructor
Student();
// The destructor
~Student();
// Set up information
int setstuinfo(int age , float score , string name);
// The print information
int Printstuinfo();
};
// Static members must be initialized
int Student::age = 24 ;
float Student::score = 86.6 ;
int Student::x = 100 ;
int Student::y = 200 ;
Student::Student()
{
this->name = "YYX" ;
cout << this->name << endl ;
cout << this->age << endl ;
cout << this->score << endl ;
}
Student::~Student()
{
this->name = "NULL";
cout << this->name << endl ;
}
int Student::setstuinfo(int age , float score , string name)
{
this->age = age ;
this->score = score ;
this->name = name ;
}
int Student::Printstuinfo()
{
cout << this->name << endl ;
cout << this->age << endl ;
cout << this->score << endl ;
}
int main(void)
{
Student stu1 ;
// Pointer to the
Student *p ;
p = &stu1 ;
p->setstuinfo(25,96,"XXX");
p->Printstuinfo();
// A reference to a static member ----> Private members cannot be referenced
cout << p->x << endl ;
cout << p->y << endl ;
Student::x = 80 ;
Student::y = 90 ;
cout << p->x << endl ;
cout << p->y << endl ;
return 0 ;
}
Operation results:
[
YYX
24
86.6
XXX
25
96
100
200
80
90
NULL
conclusion