C + + initial order -- introduction of inline functions, ranges and classes

Posted by jbx on Thu, 23 Dec 2021 01:26:30 +0100

Today is the beginning of the previous issue(1),Tell me something else C++Elementary knowledge points

1, Inline function
In order to avoid frequently used small functions, both C and C + + have their own methods to establish stack frames. C provides macros (#define), which are expanded in the preprocessing stage; C + + provides inline functions, which define frequently called small functions as inline, which will expand the function where it is called without stack frame overhead

Use examples:

inline Add(it a, int b)
{
	return a + b;
}
int main()
{
	...
}

However, we do not recommend defining all functions as inline. See the following example:

More instructions means that the compiled executable program becomes larger, occupies more memory, and the user experience becomes worse.
Therefore, the following points should be noted when using inline functions:
(1) It is a space for time method. If the code is very long or contains loop \ recursion, it is not suitable to use inlining
(2) Declaring inline is only a suggestion to the compiler, which will optimize itself. When the code is very long or contains circular recursion, even if the inline compiler is declared, it will not expand
(3) The function declared by inline cannot be separated from the declaration and definition, and a link error will occur

2, Range for
The range for is another traversal method different from the ordinary for loop. Before talking about the range for, I want to introduce the auto keyword.
·auto keyword
1. Usage examples:

int main()
{
	int a = 10;
	auto b = a;//When the type is declared as auto, the compiler can automatically deduce the type of b according to the type of a

	return 0;
}
int main()
{ 
	int x = 10;
	auto a = &x;//The type of a is int*
	auto* b = &x;//The type of b is int*
	int& y = x;//The type of y is int 
	auto c = y; 
	auto& d = x;//The type of d is still int, but a reference where d is x is specified
	return 0;
}  

2. Precautions for using Auto:
(1) auto cannot be used as a function parameter

void TestAuto(auto a)//error!
{}

(2) auto cannot be used to declare arrays

void TestAuto()
{
   int a[]={1,2,3};
   auto b[]={4,5,6};//error!
}

After a general understanding of the auto keyword, let's talk about its most common advantageous usage:
·Range for loop

int main()
{
	//Ordinary array traversal method
	int array[] = { 1,2,3,4,5 };
	for (int i = 0; i < sizeof(array); ++i)
	{
		cout << array[i] << endl;
	}

	//Range for: automatic traversal. Take out the elements in the array at one time and assign them to e until the end
	for (auto e : array)
	{
		cout << e << "";
	}	
}

Note that the above basic range for can only be read but not written, that is, the data in arr cannot be modified

for (auto e : array)
	{
		e *= 2;
		cout << e << "";//The array is still 1 2 3 4 5
	}

The reason is that the essential meaning of the range for is to copy each element in the array into e at one time, and then perform the operation on E
Therefore, if you want to modify the value of array, you need to use reference

for (auto& e : arr)
{
	e *= 2;
	cout << e << "";//array becomes 2 4 6 8 10
}
return 0;
}

3, Class introduction
There are structures in C language. For example, we can use structures to realize simulation stack:

typedef int STDataType;
struct Stack
{	STDataType* a;
	int size;
	int capacity;
};
void StackPush(...)//Stack pressing
void StackPop(...)//Out of stack
void Stacktop(...)//Fetch stack top data

It can be found that variables and implementation functions in the structure are separated, and the focus is on the process, that is, how to implement each interface function
Therefore, we also say that C language is process oriented

C + + classes are upgraded versions of structures and are compatible with all features of structures
Class contains member variables and member functions, which are no longer separated

·Access qualifier

The access qualifiers of classes are divided into public, private and protected

·Class

class Stack
{
public:
	void Init(int InitSize = 4);
	void Push(STDatatye x);
private:
	STDataType* a;
	int size;
	int capacity;
};

int main()
{
   Stack s1;
   cout<<sizeof(s1)<<endl;//12
   return 0;
}

When calculating, only the size of member variables (and memory alignment) shall be considered, excluding member functions.
This is because member functions are not stored in individual objects, but in common areas (code segments), which is a means to avoid memory waste.
In addition to this, the class size calculation is completely consistent with the structure size calculation
Attachment: calculation rules of structure size:

·Scope of class
Class defines a new scope in which all members of the class are in. Class name is required to define class objects or implement class functions outside the class:

class Person
{
public:
void PrintPersonInfor();
private:
char _name[20];
char _gender[3];
int _age;
};

void Person:: PrintPersonInfor()
{
    cout<<_name<<_gender<<_age<<endl;
}

·this pointer
In the Init function in the figure below, there is a hidden parameter: this pointer
We can't write this parameter in the parameter list, but we can use it in the function body

class data
{
private:
	int _year;
	int _month;
	int _day;
public:
	void Init(int year, int month, int day)
	{
		//The this pointer points to the parameters in the passed object
		this->_year = year;//This - > can be omitted to avoid conflicts between formal parameters and member variables with the same name
		this->_month = month;
		this->_day = day;
	}
};
int main()
{
	data d1;
	d1.Init(2021, 3, 15);
	return 0;
}

Let's deepen our understanding of this pointer through an example:

//Can the following program run successfully?
class a
{
public:
	void printa()
	{
		cout << _a << endl;
	}

	void show()
	{
		cout << "show()" << endl;
	}
private:
	int _a;
 };
int main()
{
	a* p = nullptr;
	p->printa();//error!  Null pointer access
	p->show(); //normal operation
	return 0;
}

analysis:
For the show function, there is no need to dereference p (this pointer to the * p object)
The print function accesses the member variables of the object_ a. The this pointer needs to be dereferenced to access_ a. This leads to an understanding reference to the null pointer and an error

Class also has a distinct feature. When we don't write anything about the member functions in the class, the compiler will automatically generate six default member functions. We'll leave this to the next C + + beginner level (3) for a detailed explanation

Topics: C++