Rebirth: I want to learn C++ Day 6

The main content of this article is const and permission issues , static keywords , friend functions and friend classes , I hope it will be helpful to everyone, please like, collect, comment and support!

Jump to more high-quality content:

Column: C++ Departure of Rebirth (The average quality score of the article is 93)

Table of contents

const and permission issues

1. const modifies built-in types

(1). const modifies ordinary variables

(2). const modified pointer variable

2. const modified custom type

3. const modified function

(1).const modified function parameters

(2). const modified function return type

4. Zoom in, zoom out, pan

The effect of static

(1). Static member variable

(2).Static member function

Friend Function & Friend Class

(1).Friend function

(2).Friend class


const and permission issues

1. const modifies built-in types

const is called a constant qualifier , which is used to limit a specific variable so that the variable cannot be modified. This is very practical in certain situations. For example, some read-only and non-writable variables can be limited by const.

(1). const modifies ordinary variables

In C++ or C language, the form of const to modify ordinary variables is as follows:

const int a = 10;

It is also possible to place const adjacent to variables

int const a = 10;

For ordinary variables, the two writing methods are the same, both restricting the a variable so that the a variable cannot be modified.

Forcibly modifying will cause compilation errors. That's what constant qualifiers do.

(2). const modified pointer variable

First give the pointer p of the variable a

int a = 10;
int* p = &a;

Two points are very important here : const directly modifies p, which will make p immutable, that is, the pointer point cannot be changed.

                                If const directly modifies *p, it will cause *p to be immutable, that is, the content pointed to by the pointer cannot be changed.

At this point, the following three const modifications to the pointer variable p will appear

(1)const int* p = &a;
等价写法:int const * p = &a;

At this time, const is in front of *p, and *p is directly modified, that is, the content pointed to by the pointer (*p) cannot be changed, but the point of the pointer (p) can be changed.

(2)int* const p = &a;

At this time, const is in front of p, and p is directly modified, that is, the pointer (p) cannot be changed, and the content pointed to by the pointer (*p) can be changed. 

(3)const int* const p = &a;

At this time, const is double qualified , both in front of *p and in front of p, that is, neither the pointer pointing to (p) nor the pointer pointing to the content (*p) can be changed. 

2. const modified custom type

const can also modify custom type objects, assign constant properties to objects, and protect member variables in objects from being modified . When a const object calls its member function, the this pointer is also of const type.

A detailed introduction to this pointer: Rebirth: I want to learn C++ on the third day (classes and objects) - Programmer Sought

Take the Date class as an example:

#include<iostream>
using namespace std;
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	const Date d1;//创建const类型对象d1
	return 0;
}

At this point, call the member function with d1

d1.Print();

Compilation errors will occur. The reason is that when a const object calls a member function, the this pointer passed to the member function is also of const type.

But at this time, the implicit parameter of the member function is the this pointer of non-const type

void Print(Date* const this)//这个const是默认的,保证指向不能改变但是指向的内容还是可以改变

The const object pointer will be passed to the non-const object pointer, which involves the amplification of permissions: the member variables of the const object cannot be modified, but the this pointer only points to and cannot be changed, and the pointed content can still be changed.

To solve this problem, you need to change the implicit parameter this pointer in the member function to const type. The following introduces the concepts of const and functions to solve this problem.

3. const modified function

(1).const modified function parameters

The role of const modified function parameters is to use const type objects to receive actual parameters to ensure that the actual parameters will not be changed . In the member function, the formal parameter also has an implicit this pointer, which is used to receive the address of the object. But since this formal parameter is implicit, we cannot directly change it to a const type. At this time, you only need to add const after the member function

void Print()const
{
	cout << _year << "/" << _month << "/" << _day << endl;
}

Equivalent to adding const to the implicit this pointer (the previous const)

void Print(const Date* const this)

In this way, the const object can call the const member function of the object. 

Here, const is added in front of *this, which means that the content of the object pointed to by this cannot be changed.

The const modification of this pointer can also constitute function overloading: when the object is called, the const object and the non-const object are respectively called

const void Print()const  //const对象调用:只读
{
	cout << _year << "/" << _month << "/" << _day << endl;
}
void Print()             //非const对象调用:可读可写
{
	cout << _year << "/" << _month << "/" << _day << endl;
}

(2). const modified function return type

The return type of the const modified function can restrict the object to ensure that the returned object cannot be changed.

4. Zoom in, zoom out, pan

In C++, permissions can only be panned, zoomed out. Zooming in is prohibited. For example:

const int a = 10;
	int& b = a;

At this point, a compilation error will occur, because a is of const type and cannot be changed. But the reference b is not a const type, and b can indirectly change a, so it will compile an error. This is the magnification of authority.

const int a = 10;
const int& b = a;

This is the translation of authority.

int a = 10;
const int& b = a;

This is the reduction of authority. 

Note: Temporary variables are generated in the middle of implicit type conversion, and temporary variables are constant.

Take a chestnut:

double d = 1.1;
int& a = d;

At this time, the compilation error is not caused by the type mismatch, but when d is assigned to an int type to refer to a, d will first be implicitly converted to a const int& type. At this time, you only need to change the code to

double d = 1.1;
const int& a = d;

It can be compiled. 

The effect of static

Definition: Class members declared as static are called static members of the class, member variables modified with static are called static member variables ; member functions modified with static are called static member functions . Static member variables must be initialized outside the class.

(1). Static member variable

A variable modified statically in a class is called a static member variable . Due to the static modification, the member variable is stored in the static area and belongs to the class. The objects used in the class are public and do not belong to an object alone (this feature is similar to member functions), so the definition of static member variables is not in the parameter list , it must be defined outside the class , and the class is responsible for the declaration of static member variables .

#include<iostream>
using namespace std;
class A
{
private:
	static int _a;//声明
};
int A::_a = 0;//类外定义
int main()
{
	A a;
	return 0;
}

(2).Static member function

A member function modified statically in a class is called a static member function . Due to the static modification, the member function belongs to the class. Since the static member function does not have an implicit this pointer, when a specific object is called, only the static member variables of the class can be accessed , and the non-static member variables of the object cannot be accessed . It can be called directly by class name::static member function name.

In addition, there are three ways to break through the class domain outside the class (friends are introduced below):

Do not use friends to access member variables or member functions must be shared.

1. Create an object, through the object .           It is suitable for accessing public (static, non-static) member variables and functions.

2. Object pointer, through pointer -> When the pointer is empty, you can access public member functions (static and non-static) and public static member variables. Because neither public member functions nor public static member variables belong to objects, there will be no error of dereferencing a null pointer . When the pointer is not null, it has the same access rights as the object.

3. By class name:: suitable for accessing public static member variables and public static member functions . Only members belonging to static properties of the class can be accessed here.

Friend Function & Friend Class

(1).Friend function

Definition: A friend function can directly access the private members of a class . It is an ordinary function defined outside the class and does not belong to any class, but it needs to be declared inside the class, and the keyword friend needs to be added when declaring. For example:

#include<iostream>
using namespace std;
class A
{
	friend void Print(A& a);//友元函数声明
private:
	int _a=1;
};
void Print(A& a)//友元函数定义
{
	cout << a._a << endl;//friend就可以直接访问类的私有成员
}
int main()
{
	A a;
	Print(a);
	return 0;
}

Note :

1. Friend functions cannot be modified with const

2. A function can be a friend function of multiple classes

(2).Friend class

The friend class can directly access the private members of the class , the friend class and another class are independent of each other, only the friend class of this class is allowed to access the private members of the class, and the class is not allowed to access the private members of the friend class.

class Time
{
   friend class Date;   // 声明日期类为时间类的友元类,则在日期类中就直接访问Time类
中的私有成员变量
public:
 Time(int hour = 0, int minute = 0, int second = 0)
 : _hour(hour)
 , _minute(minute)
 , _second(second)
 {}
   
private:
   int _hour;
   int _minute;
   int _second;
};
class Date
{
public:
   Date(int year = 1900, int month = 1, int day = 1)
       : _year(year)
       , _month(month)
       , _day(day)
   {}
   
   void SetTimeOfDate(int hour, int minute, int second)
   {
       // 直接访问时间类私有的成员变量
       _t._hour = hour;
       _t._minute = minute;
       _t._second = second;
   }
   
private:
   int _year;
   int _month;
   int _day;
   Time _t;
};

Friend class features :

1. The friendship relationship is one-way and not exchangeable. For example, the above-mentioned Time class and Date class declare Date class as its friend class in the Time class, then you can directly access the private member variables of the Time class in the Date class, but want to access the private member variables of the Date class in the Time class not.

2. The friendship relationship cannot be transmitted. If C is a friend of B and B is a friend of A, it cannot be explained that C is a friend of A.

3. The friendship relationship cannot be inherited.

That's all for today's sharing. If it is helpful to everyone, remember to bookmark it. I hope that programmers can support the following three times and continue to share knowledge! thanks for reading!

Guess you like

Origin blog.csdn.net/2301_76144863/article/details/132015711