Essay -- Summary of preliminary questions of classes and objects (interview)

The difference between object oriented and process oriented

C language is process oriented and focuses on the process. It analyzes the steps to solve the problem and solves the problem step by step through function call. Process oriented is to analyze the steps required to solve the problem, and then use the function to realize these steps step by step. When using, it can be called one by one.
C + + is based on object-oriented and focuses on objects. It divides a thing into different objects and completes it by the interaction between objects. Object-oriented is to decompose the problem-making transactions into various objects. The purpose of establishing objects is not to complete a step, but to describe the behavior of something in the whole problem-solving step.

Three characteristics of object-oriented

Three characteristics: inheritance, encapsulation and polymorphism

encapsulation

1. Integrate variables (attributes) and functions (operations) into a whole and encapsulate them in a class
2. Access control of variables and functions.
Purpose: the purpose of encapsulation is to ensure the security of variables. Users do not have to care about the specific implementation details, but can access the members of the class through the external interface

inherit

Inheritance: it can use all the functions of existing classes and extend them without rewriting the original classes.
A very popular example is that you first abstract an object of the person class
It has
class person
{
public:
person()
{
}
private:
string name;
int age;
char gender[2];
}
Then, create different classes according to different people to inherit the person class, because the attributes provided by the person class are the characteristics of everyone. At this time, if you create a class again, you can make a simple expansion relative to the person class. With so much nonsense, the essential purpose is to improve the reuse rate and scalability of the code.

polymorphic

Concept:
(1) Determine the specific target of function call according to the actual object type;
(2) The same call statement has many different manifestations in actual operation, which is polymorphism. The same statement has many forms.
Example: proposal of template
The purpose of polymorphism is to realize dynamic binding, which makes the program run more efficiently and easier to maintain and operate.

const keyword

const modifier ordinary variable

1. In C language, the data defined in the global variable cannot be changed, but the data defined on the stack (generally speaking, the const variable defined in the function body) can be modified.
2. In C + +, the data of global variables cannot be modified, but the data inside the function body can be modified formally, but in essence, you can't affect its value. The grammar is right, but it's useless.
The reason is because constant folding
Usually, the C + + compiler does not create storage space for const. Instead, it saves this definition in its symbol table. It is equivalent to replacing b with 20 when compiling, so even the modification has no effect on it at this time. It depends on the case that const variable is internally connected. If the external connection is addressed, or the volatile keyword is added, or the const variable is used as an lvalue, the compiler will not collapse the constant at this time, because what is needed at this time is a real constant address.
The specific reasoning process is put in First acquaintance C++ In this blog.

const modifies class members and class member functions

Distinguish between initialization and assignment

Distinguish between constructor initialization and assignment
Initialization: can only be initialized once
Assignment: multiple assignments can be made
For example, const int a=10// This is initialization, because it can only use this value from creation to the end of its life cycle.
And int a=10; a=20;// This is assignment. As long as it is defined and the memory in it is not recycled, it can be assigned multiple times.
First, let's look at the assignment operation:

Let's look at the example of date:

initialization
Initialization list: start with a colon, followed by a comma separated list of data members. Each "member variable" is followed by an initial value or expression in parentheses

const modifier member variable

There are two ways to define:

const modifier member function

Method 1: modify the return value

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

	~date()
	{

	}
	const date* operator&()
	{

		cout << this << endl;
		return this;
	}

private:

	int year;
	int month;
	int day;
};
int main()
{
	date s(2021, 6, 22);
	const date* p = &s;
	cout << p << endl;
}

Note: if the return value of the function is const type, the variable receiving it should also be const type. This is to modify the return value so that the person receiving it cannot modify it at will, but he can modify it internally when calling.

const modifies this pointer

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

	~date()
	{

	}
	const date* operator&()const
	{
		//this->day = 100;err
		//this->year = 2000;err
		cout << this << endl;
		return this;
	}

private:

	int year;
	int month;
	int day;
};
int main()
{
	date s(2021, 6, 22);
	const date* p = &s;
	cout << p << endl;
}

Analysis of extern "C"

Why put forward extern "C"

The main function of extern "C" is to realize that c + + code can call other c language code. After adding extern "C", this part of the code compiler compiles and links in the way of c language, rather than in the way of c + +.
Essential reason: the aliases of the two functions are different. At this time, the names named according to the naming rules of c + + cannot be found when looking for c language functions. First, let's see how they are named at the bottom.
All experimental results are based on Linux, and different compilers have different results
C language naming

#include <stdio.h>
int add(int a, int b)
{
	return a + b;
}

int main(void)
{

	system("pause");
	return 0;
}


C + + naming

#include<iostream>
using namespace std;
int add(int a, int b)
{
	return a + b;
}
int add(int a)
{
	return a+10;
}
int main(void)
{

	
	return 0;
}

How to use extern "C"

test.h file

#pragma once
#include<stdio.h>
//Tell the C + + compiler that I need to find this function in the way of C language
#ifdef __cplusplus
extern "C"
{
#endif;
	int add(int a, int b);

#ifdef __cplusplus
}
#endif 

test.c Documents

#pragma once
#include "test.h"
int add(int a, int b)
{
	return a + b;
}

main function file

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
#include"test.h"
int main()
{
	cout << add(10, 20) << endl;
	system("pause");
	return 0;
}

References and pointers

The essence of reference

Essence: alias variables
int &a=b;
The bottom layer will change it to int * const a = & B; This also explains why references must be initialized
a=100;// At this time, the compiler finds that a is a reference to b, and the bottom layer will do this * a = 100;

The difference between reference and pointer

Essence: a reference is an alias, a pointer is an address,

① Phenomenally, the pointer can change the value it points to at run time, while the reference will not change once it is bound to an object. The pointer can be reassigned to point to a different object. However, the reference always points to the object specified during initialization and cannot be changed later, but the content of the specified object can be changed.
② In terms of memory allocation, the program allocates a memory area for pointer variables instead of references, because references must be initialized when declared, so as to point to an existing object. A reference cannot point to a null value.
Note: the standard does not specify whether a reference should occupy memory or how to implement it,
③ In terms of compilation, the program adds pointers and references to the symbol table respectively when compiling. The symbol table records the variable name and the address corresponding to the variable. The address value corresponding to the pointer variable on the symbol table is the address value of the pointer variable, while the address value corresponding to the reference on the symbol table is the address value of the reference object. After the symbol table is generated, it will not be changed. Therefore, the pointer can change the object pointed to (the value in the pointer variable can be changed), while the reference object cannot be changed. This is the main reason why using pointers is unsafe and using references is safe. In a sense, a reference can be considered an immutable pointer.
④ The fact that there are no references to null values means that code using references is more efficient than using pointers. Because you don't need to test the legitimacy of a reference before you use it. Instead, the pointer should always be tested to prevent it from being empty.
⑤ Theoretically, there is no limit to the number of pointers, but the reference can only be one level. As follows:
int** p1; // Legal. Pointer to pointer
int*& p2; // Legal. Reference to pointer
int&* p3; // Illegal. Pointer to reference is illegal
int&& p4; // Illegal. A reference to a reference is illegal
Note that the above pronunciation is from left to right.

Implement a singleton pattern based on static member functions / variables

Singleton mode

Definition of singleton pattern: a class can only initialize one object
Design idea of singleton mode:
1. Privatize the parameterless constructor and copy constructor
2. Define static member pointers within a class
3. When initializing outside the class, new an object
4. Set the permission of the pointer to private, and then provide a static member function to let the outside get the pointer

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
class student
{
private:
	//1. Privatize the parameterless constructor and copy constructor
	student()
	{

	}
	student(const student& m1)
	{

	}
	//4. Set the permission of the pointer to private, and then provide a static member function to let the outside get the pointer
public:
	static student* get()
	{
		return p;
	}
private:
	//2. Define a static intra class member pointer
	static student* p;
};
//3. Define outside the class
student* student::p = new student;
void test01()
{
	student* m = student::get();//Provide an interface function to avoid the user's wrong modification of the member pointer in the class
	student* m1 = student::get();
	cout << "*m1  " << m1<< endl;
	cout << "*m  " << m << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

Single case pattern design example

Objective: to obtain the number of prints

//Obtain the printing times of the printer according to the requirements
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
class print
{
private:
	//1. Privatize the parameterless constructor and copy constructor
	print()
	{
		mount = 0;
	}
	print(const print& m1)
	{

	}
public:
	//Use static member functions to return pointers
	static print* get()
	{
		return p;
	}
	 void dayin(string name)
	{
		cout << name << "Print" << endl;
		mount++;
	}
	int return_num()
	{
		return mount;
	}
private:
	static print* p;//2 declare a static member pointer
	int mount;
};
print* print::p = new print;//3 declare a static member pointer
void test()
{
	print *m1 = print::get();
	m1->dayin("Production department");
	print* m2 = print::get();
	m2->dayin("R & D department");
	print* m3 = print::get();
	m3->dayin("Marketing Department");
	cout << "Printing times" << m3->return_num() << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

Usage scenario of singleton mode

Task manager, a computer can only open one task manager no matter what.

volatile keyword

Application: it is widely used in embedded system
Function: tell the compiler that the variable may change. You must get it from memory every time you use the value. Not in registers
It is understood as follows: if an interrupt occurs in the embedded system, the value of the register is modified at this time, and you go to get the data at this time, the value obtained at this time is usually what we commonly call "dirty data".

const combined with volatile

const volatile int a=0;// Tell the compiler that the program cannot modify it, but can only be rewritten by the cpu.
const volatile means that the variable can neither be modified nor optimized to a register, that is, it may be modified in a way unknown to other compilers. For example, a real-time clock, which we do not want to be modified by the program, should be declared as const, but other threads and interrupts (possibly from the Library) have to modify the value of the clock at this time. The compiler cannot optimize it as const constant into the register, so it should be declared as volatile.

explicit keyword

The explicit keyword prevents the compiler from optimizing statements that need to be optimized
This has been summarized before. You can go to my blog to see it in the last item.
explicit keyword

Keywords: C++ Programming pointer

Added by pilau on Thu, 27 Jan 2022 19:05:28 +0200