Learning notes on special member variables in C + + classes

Keywords: C++ OOP

It is said that the roommate static member variable does not know its role, and it is also said that the roommate const is not very good. I wrote this study note with my backhand. The data members in a class not only have int s and char s, but also describe many complex situations. The data members in a class may need to be shared among multiple objects, or they may only be read in objects and cannot be modified. So this blog post is to explain two kinds: 1. Static for sharing data types; 2. Const for reading but not modifying

1. Modify data members with static

If the specific data is in memory and can be shared by all members of a class, for example, when designing a student class, you can set an attribute to count the total number of students. Using static data members can realize the data sharing and interaction of multiple objects in the class. The values of static data members are the same for each object and can be updated. As long as the values of static data members are updated, all objects will get the updated values.
In C + +, data members decorated with static are called static members. The specific definition form is as follows:

static Type identifier static data member name;

For static data members, if they are declared to have public attribute, they can be accessed outside the class through objects, similar to ordinary public data members. The access form is as follows:

object.Public static data member = xx;

However, since the static data member does not belong to any object, there is a unique way to access the static data member. It can be accessed directly through the class name instead of through the class object. This way is usually adopted. The access form is as follows:

Class name::Static data member name

If you want to initialize a static data member, you need to provide an initial value outside the class through the method "class name:: static data member = initial value". The initialization form is as follows:

Class name::Static data member=initial value;

1.1 case – create student count


#include<iostream>
#include<cstring>

using namespace std;

class Date{ //Date class definition
public:
    Date(int y,int m,int d);  //Declare a constructor with parameters
    Date(Date &con_date);   // Declare copy constructor
private:
    int m_nYear,m_nMonth,m_nDay;

};

Date::Date(int y,int m,int d):m_nYear(y),m_nMonth(m),m_nDay(d) { //Defines a constructor with parameters for the Date class
    cout << "Date constructor!" << endl;
}

Date::Date(Date &con_date) { //Defines the copy constructor for the Date class
    m_nYear = con_date.m_nYear;
    m_nMonth = con_date.m_nMonth;
    m_nDay = con_date.m_nDay;

}

class Student {  //Define Student class
public:
    static int s_nTotalNum;   //Static data member
    Student(char *con_name,int con_id,Date&con_birthday);
    ~Student();
private:
    char m_gName[20];
    int m_nID;
    Date m_iBirthday;
};

//Defines the constructor with parameters for the Student class
Student::Student(char *con_name,int con_id, Date &con_birthday): m_iBirthday(con_birthday) {
    int namelen = strlen(con_name) + 1;
    strcpy_s(m_gName,namelen,con_name);
    m_nID = con_id;
    s_nTotalNum++;//For each object constructed, 1 is added
}

Student::~Student() //Destructor
{
    s_nTotalNum--;
    cout << "destructor,totalnum = " << s_nTotalNum << endl;
    if(s_nTotalNum == 0)
        system("pause");
}

int Student::s_nTotalNum = 0; //Initialization of static data
int main()
{
    Date tombirthday(1998, 5, 20);
    //Create a Student object
    Student std_tom("Tom",1,tombirthday);
    cout << "Tom,the totalnum = " << std_tom.s_nTotalNum << endl;

    Date paulbirthday(1998, 4, 12);
    Student std_paul("paul",2,tombirthday);
    cout << "Paul, the totalnum = " << std_paul.s_nTotalNum << endl;
    return 0;

The main function creates two objects, and the running result shows that each object created is s_nTotalNum increases by 1. If the life of an object ends, the static data member decreases by 1

2. Decorate data members with const

Sometimes, if you want the data members in the class not to be changed during the use of objects, you can define such members as constant data members. For example, define a class representing a circle, and the pI value of PI will be used in the class. The common forms are as follows:

class Class name
{
	const Data type data member;
};

Constant data members must be initialized and cannot be updated. Ordinary data members can give initial values in the constructor through the initialization table or assignment statements in the function. If you want to initialize constant data members, you can only complete them through the initialization table and cannot assign values inside the constructor. The initialization method of constant data members is as follows:

Class name:: Class name(parameter list ):Constant data member 1(value),Constant data member 2(value){
	Constructor body
}

2,1 use const to calculate the area of a circle

#include<iostream>
using namespace std;

class Circle {
public:
    Circle(double con_radius);
    double circumference();
private:
    double m_fRadius;
    const double PI; // Constant data member describing pi
};

//Define the constructor, and the constant data members are initialized through the initialization table
Circle::Circle(double con_radius):PI(3.14){
    m_fRadius = con_radius;
}

double Circle::circumference() {
    return 2 * PI * m_fRadius;
}

int main()
{
    Circle c1(2);
    cout << "circumference:" << c1.circumference() << endl;
    system("pause");
    return 0;

}

The code is more conventional. Initialize the constants in the initialization table, then calculate according to the conventional idea, and finally print the results.

3. Summary

In this blog post, static and const are proposed to describe different complex situations. Static generally means that multiple objects share the same memory. It is mostly used for constructor initialization and destructor deconstruction. Const must be initialized. Initialization cannot be assigned within the function, and it is basically assigned in the definition table. Examples are more popular. Of course, you can collect what you need.

Posted by TheHeretic on Wed, 24 Nov 2021 05:29:06 -0800