Explain C + + classes and objects in detail

Initialization list

The initialization member list is used as follows, taking the date class as an example.

class Date
{
public:
	Date(int year, int month, int day):_year(year),_month(month),_day(day)
	{}
private:
	int _year;
	int _month;
	int _day;	
}

The initialization list call occurs when the object is defined. The constructor body of the above code is empty. Of course, the initialization list can also be mixed with the initialization in the function body.

It should be noted that:

  1. Each member variable can only appear once in the initialization list.
  2. Class contains reference member variables, const member variables and custom member variables (there is no default constructor), which must be initialized in the initialization list.
  3. The order in which member variables are declared in the class is the order in the initialization list.

For point 3, you can run the following code to get unexpected results.

class A
{
public:
	A(int a):_a1(a),_a2(a1)
	{}
private:
	int _a2;
	int _a1;
};
int main()
{
	A aa(2);
}

Running result: the two member variables of aa will not be initialized to 2. Actually_ a2 will be initialized first, so_ The value of a2 is a random value_ The value of a1 is 2.

Static member

Static members are declared in the class as follows

class A
{
	static GetN()
	{
		return _n;
	}
private:
	static int _n;
}

Where, static variable_ n exists in the static area and belongs to both the whole class and all objects of the class. The same is true for static member functions. When initializing static member variables, you can use the following form

int A::_n = 0;

Therefore, variables that appear to be defined in a class are actually just declarations of variables. In other words, static member variables must be defined outside the class. The method of definition can be static, and the class name can be static.

It should be noted that static member functions do not have a hidden this pointer and cannot access non static members.

Friends

Friends destroy the encapsulation of object-oriented. Therefore, it is not suitable for large area use. By declaring friend functions in a class, there is no difference between accessing members outside the class and inside the class.

# include <iostream>
class Date
{
    friend std::istream& operator>>(std::istream& in, Date& date);
public:
    int GetMonthDay(int year, int month)
	{
		static int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
			days[2] += 1;
		}

		return days[month];
	}
    Date(int year=0, int month=0, int day=0):_year(year),_month(month),_day(day)
    {}
    bool operator>(const Date& d)
    {
        if (_year > d._year)
        {
            return true;
        }
        else if (_year == d._year)
        {
            if (_month > d._month)
            {
                return true;
            }
            else if (_month == d._month)
            {
                if (_day > d._day)
                {
                    return true;
                }
            }
        }
        return false;
    }
    bool operator==(const Date& d)
    {
        return _year == d._year && _month == d._month && _day == d._day;
    }
    bool operator<(const Date& d)
    {
        return !((*this)>d || (*this)==d);
    }
    
    Date& operator++()
    {
        _day += 1;
        while (_day > GetMonthDay(_year, _month))
        {
            _day -= GetMonthDay(_year, _month);
            _month++;

            if (_month > 12)
            {
                _year++;
                _month = 1;
            }
        }
        return *this;
    }
    int operator-(const Date& d)
	{
		Date max = *this;
		Date min = d;
		int flag = 1;
		int n = 0;

		if (min > max)
		{
			max = d;
			min = *this;
			flag = -1;
		}

		while (min < max)
		{
			++min;
			n++;
		}
		
		return n * flag;
	}
private:
    int _year;
    int _month;
    int _day;
};
std::istream& operator>>(std::istream& in, Date& date)
{
    scanf("%4d%2d%2d", &date._year, &date._month, &date._day);
    return in;
}
int main()
{
    Date d1;
    Date d2;

    std::cin >> d1 >> d2;
    std::cout << abs(d1 - d2) + 1 <<std::endl;
    return 0;
}

The above code is to solve the number of days between two dates. This class overloads the input operator. The private member variable of the date object can be accessed outside the class by declaring it with the keyword friend inside the class_ year,_month,_day.

Similarly, if you declare another class as a friend in a class, another class can access its private members, as shown in the following code.

class Add
{
    friend class Solution;
public:
    Add()
    {
        _ret += _i;
        _i++;
    }
private:
    static int _i;
    static int _ret;
};
int Add::_i = 1;
int Add::_ret = 0;
class Solution {
public:
    int Sum_Solution(int n) {
        Add::_i = 1;
        Add::_ret = 0;
        
        Add arr[n];
        return Add::_ret;
    }
};

Tags: C++ Programming encapsulation Class

Posted by serenade2 on Sun, 16 Jan 2022 06:26:46 +1030