C + + problems

Posted by djkanebo on Wed, 22 Sep 2021 04:11:14 +0200

Qs

What does the Q1 namespace do?
What is the difference between Q2 cout output and printf output? Respective advantages and disadvantages?
When cin is entered, it ends with a space by default

cout "<<"The operator is overloaded and output according to the data type to be output, printf Is to manually operate the output content format.
printf The running time is shorter but troublesome.

Q3 endl action? How to avoid auto wrap?

endl Represents a newline symbol.

Q4 enumeration types, applicable scenarios and methods?

Q5 defines constants in two ways: macro definition #define and const keyword. What's the difference?

// #deine form:
#define identifier value
// const keyword form
const type variable = value;

Constants are usually all uppercase
difference:

  1. const constants define both types and variables, and define only constants.
  2. const works at compile and run time, and define works at compile preprocessing *.
  3. define is just a simple character replacement. identifier=value will be replaced in the preprocessing stage, so it cannot be debugged and memory will not be allocated, but const can.
  4. const cannot be redefined, but define can be #undef undefined.
  5. ***define prevents repeated references to header files***
  6. const must be given an initial value when it is defined, except when it is decorated with extern (extern is a global declaration keyword).

Q6 what is the difference between pointer "*" and reference "&"?

  • Pointer is a variable, which stores the address of the storage unit in memory, and reference is the alias of the original variable.
  • Can have const pointer.
  • Pointers can have multiple levels, but references can only have one level.
  • The value of the pointer can be null, but the referenced value must be initialized at the time of definition and cannot be null.
  • The value of the pointer can be modified after initialization, but the referenced value cannot be modified after initialization.
  • The meaning of self increment (+ +) and self decrement (–) operation of pointer and reference is different. Pointer is to operate the direction of data, and directly operate the data during reference.
1.  #include <iostream>
2.  using namespace std;

3.  int main (){
4.      int a = 10;
5.      int &r = a;
6.      r++;
7.      cout<<r<<endl;

8.      int arr[2] = { 27, 84 };
9.      int *p = arr;
10.      p++;
11.      cout<<*p<<endl;
12.      return 0;
13.  }

Output:
	11
	84

What is the role of Q7 static?

  • When modifying a global variable, it indicates that a global variable is only visible to functions defined in the same file.
  • When decorating a local variable, it indicates that the value of the variable will not be lost due to the termination of the function.
  • When modifying a function, it is shown that the function is only invoked in the same file.

What do Q8 output buffer stream and non buffer stream mean respectively?

A buffer stream is an output stream. It will be stored in the buffer until the buffer is full or refreshed.

What is the difference between Q9 Heap and Stack?

  • Stack memory is automatically managed by the program. It exists in C + + in the heap and needs to be managed through new and delete.
  • Inline function?? Why is it recommended that functions be defined outside the class??

Class declaration and member function definition are part of class definition. In actual development, we usually put the class declaration in the header file and the member function definition in the source file.

Q9 folding function
Q10 friend functions and friend classes
Q11 inline function

Ns

N1: the modifier volatile tells the compiler that variables declared by volatile do not need to be optimized, so that the program can read variables directly from memory. For general variables, the compiler will optimize the variables and put the variable values in memory in registers to speed up the reading and writing efficiency.

N2 storage class

  1. The register storage class is used to define local variables stored in registers rather than RAM. This means that the maximum size of the variable is equal to the size of the register (usually a word), and the unary '&' operator cannot be applied to it (because it has no memory location). Due to the limitation of hardware, it may also be placed in RAM.
  2. The static storage class instructs the compiler to maintain the existence of local variables throughout the life cycle of the program without creating and destroying them every time it enters and leaves the scope.
  3. The extern storage class is used to provide a reference to a global variable that is visible to all program files.
  4. The mutable specifier applies only to objects of a class, which will be explained at the end of this tutorial. It allows members of objects to replace constants. That is, mutable members can be modified through const member functions.
  5. Using thread_ The variable declared by the local specifier is accessible only on the thread on which it is created. Variables are created when the thread is created and destroyed when the thread is destroyed. Each thread has its own copy of the variable. And can be used with static and extern.

N3 Switch statement

switch(expression){
    case constant-expression  :
       statement(s);
       break; // Optional
    case constant-expression  :
       statement(s);
       break; // Optional
  
    // You can have any number of case statements
    default : // Optional
       statement(s);
}

be careful:

  • The expression in the switch statement must be an integer or enumeration type, or a class type, where class has a single conversion function to convert it to an integer or enumeration type.
  • The constant expression of case must have the same data type as the variable in switch, and must be a constant or literal.

-[] Lambda functions and expressions

N4 built in mathematical function

Library file (cmath)

  • Double pow (a, b) B power of a
  • Arithmetic square root of double sqrt(a) a
  • int abs(a) returns an integer absolute value
  • double fabs(a) returns the absolute value of a floating point number
  • double floor(a) rounded down
  • double ceil(a) round up

N5 random number (pseudo)

The random generator is generated by algorithm according to the description of system time.

Library files:
Pseudo decision function: srand(times);

N6 setw() and setfill() functions

Library files (iomanip)

setw() sets the width of the input after it,

cout << setw(len) << output1 << endl;
If len is longer than output1, it will be filled in with spaces by default, otherwise all outputs will be made.
cout << setfill(*) << setw(len) << output1 << endl;

example:
cout << setw(10) << "12345" << endl;
cout << setfill('*') << setw(10) << "12345" << endl;
Output:
     12345
*****12345

Relationship between N7 array and pointer

double *p;
double array[10];
p = array;

Pointer to & array [0] for the thing represented by array.
At the same time * (p+1) = array[1]

Example:
	double *p;
    double array1[] = {10, 2, 3, 4};
    p = array1;
    cout << *p << endl;
    cout << *(p+1) << endl;
Output:
	10
	2

Differences between N8 struct and class

  • The member attribute of class is private by default, and struct is public by default.
  • class inheritance is private by default, and struct is public by default.
  • class can use templates.

N9 outputs specific hexadecimal data

 example:
 	int a = 90;
  	cout<<hex<<showbase<<a<<endl;
 Output:
 0x5a

hex means to output in hexadecimal, and showbase means to add the hexadecimal prefix 0x.
N10 about pointers and references

  • The pointer can only point to memory. If the data is in a register or hard disk, it cannot get the address (some temporary variables, the result of an expression or the return value of a function).
  • The constant expression does not contain variables (the result is an immediate number), which will be evaluated at the compilation stage and "hard coded into instructions" and cannot be addressed.
  • Under GCC, references cannot refer to any temporary data.
  • Under Visual C + +, references can only refer to temporary data in memory (non code area).

enumeration

give an example:

enum type{sign1 , sign2=4, sign3 }name;
cout << sign1 << sign2 << sign3 << endl;
# output: 045 
# In the enumeration, the data type is int, the default starting value is 0, and the subsequent values are incremented by 1 by default (without assignment)

variable

The name of a variable can consist of letters, numbers, and underscore characters, and must begin with a letter or underscore

  1. extern: Global declaration variable
  2. Constant: Boolean value: true, false;

operator

1. Logical operators

"&&" Logic and
"||" Logical or
"!" Logical non

2. Bitwise operator

"&" Bit and
"|" Bit or
"^" XOR
"~" Reverse
"<<" Left shift
">>" Right shift
A = 0011 1100
B = 0000 1101
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
A << 2 = 1111 0000 

Both arithmetic and bitwise operators can be combined with "=" to form an assignment operator

-=
<<=
&=
^=
  1. Miscellaneous operator
1 sieoof()  Returns the byte size of the variable
2 Condition?X:Y Three eyes/Conditional operator, if Condition If true, the value is X,Otherwise Y. 
3 "," Returns the value of the last expression after a series of operations.
4 "./->" Member operator, applicable when accessing structure members“.",Applicable when accessing structure members through pointers“->". 
5 The strong conversion operator can convert operators that are not limited to constants.
6 "&" Returns the address of the variable
7 "*" Pointer operator, pointing to the address of the pointer,

*a Indicates that it will a Take out the contents of.
&b Indicates that it will be removed b The address of the variable.

C + + pointer

1 pointer declaration

 When declaring a pointer, there is no exact address to“ NULL"Assignment, which is called null pointer, and the value it represents is 0 in the standard library;

2 arithmetic operation of pointer

 It can be decremented or incremented, and the change size is the number of bytes of its data type. 

3 pointer array

int *ptr[3] = {&name1, &name2, &name3};  ptr All elements in the are one point int Pointer to value.
char *names[3] = {"zhang", "Ha", "As"};

In the above ex amp le, except for char array or String type, the address character "&" needs to be added before other right-hand data types, because the variable names of char array and String type are equal to the addresses of array and String.

 The array name represents the address of the first element of the array

4 multilevel indirect addressing
5 pointer transfer parameter
6 function return pointer

1)The function type needs to be declared as pointer type, such as: int * myFunction(). 
2)The address of a local variable cannot be returned unless the local variable is defined as static Variable.

this in the class is a const pointer, and its value cannot be modified. All operations that attempt to modify the pointer, such as assignment, increment, decrement, etc., are not allowed. this is meaningful only after the object is created, so it cannot be used in static member functions.

C + + reference

The reference is an alias of a stored variable. It must be initialized when declaring. There is no empty reference and cannot be modified after initialization (the address cannot be modified, but the content can be modified)

Example:
  	int a = 100, aa = 1000;
    int &b = a;
    cout << b << "-----"<< &b <<  endl;
    b = aa;
    cout << b << "-----"<< &b << endl;
Output:
	100-----0x61fe04
	1000-----0x61fe04
 Counterexample:
	 int &b = a;
   	 &b = aa;  # Modifying references is not allowed.

Time and date

Library file - (ctime)

Input and output

The library file is (iostream)

  1. cin
  2. cout
  3. cerr output, unbuffered stream
  4. Clock output, buffered stream

structural morphology

#include <iostream>
#include <cstring>
 
using namespace std;
void printBook( struct Books book );
 
// Declare a struct type Books 
struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};
 
int main( )
{
   Books Book1;        // Defines the variable Book1 of the structure type Books
   Books Book2;        // Defines the variable Book2 of the structure type Books
 
    // Book1 details
   strcpy( Book1.title, "C++ course");
   strcpy( Book1.author, "Runoob"); 
   strcpy( Book1.subject, "programing language");
   Book1.book_id = 12345;
 
   // Book2 details
   strcpy( Book2.title, "CSS course");
   strcpy( Book2.author, "Runoob");
   strcpy( Book2.subject, "front-end technology");
   Book2.book_id = 12346;
 
   // Output Book1 information
   printBook( Book1 );
 
   // Output Book2 information
   printBook( Book2 );
 
   return 0;
}
void printBook( struct Books book )
{
   cout << "Book title : " << book.title <<endl;
   cout << "Book author : " << book.author <<endl;
   cout << "Book category : " << book.subject <<endl;
   cout << "book ID : " << book.book_id <<endl;
}

Classes and objects

1 Definition

Objects can be created in two ways

1. It is created on the stack. Its form is similar to that of ordinary variables. It needs to be used to obtain the address“&",Use when accessing members“.";
2.  Use on heap new Keyword creation, and must have**Pointer pointing**It,**Use when accessing members“->"**. 

example:

Class Student{
public:
	stirng name;
	ing age;
};
# First kind
Student stu;
stu.name = "xiaoming";
# Second
Student &stu1 = new Student;
stu1-> name = "xiaoming";

2 member variables and functions

definition:

  • Class cannot assign values to member variables.
  • Member functions can be defined outside the class using the domain resolver "::" but must be declared in the class in advance.
  • If the member access permission is not declared, it defaults to private.

Example:

class Student{
public:
    char *name;
    int age;
    float score;
    void say();
};
void Student::say(){
    cout<<name<<"What is your age"<<age<<",The result is"<<score<<endl;
}

Most of the member variables start with m_ which is a conventional way of writing, not the content specified by grammar.
Anonymous objects cannot reclaim memory, which will lead to memory leakage

3 constructor

#include <iostream>
using namespace std;

class Student{
private:
    char *m_name;
    int m_age;
    float m_score;
public:
    //Declaration constructor
    Student(char *name, int age, float score);
    //Declare normal member functions
    void show();
};

//Define constructor
Student::Student(char *name, int age, float score){
    m_name = name;
    m_age = age;
    m_score = score;
}
//Define normal member functions
void Student::show(){
    cout<<m_name<<"What is your age"<<m_age<<",The result is"<<m_score<<endl;
}

int main(){
    //Pass arguments to constructor when creating object
    Student stu("Xiao Ming", 15, 92.5f);
    stu.show();
    //Pass arguments to constructor when creating object
    Student *pstu = new Student("Li Hua", 16, 96);
    pstu -> show();

    return 0;
}
Constructor must be public Type.

Overload of constructor

  • In the case of multiple constructors, the function corresponding to the argument is automatically matched when the object is created.
  • When using no custom constructor, the compiler automatically generates an empty constructor.

constructor initializer list

The assignment order of the member variable list is independent of the list data and is determined by the declaration order in the class.

class Student{
private:
    char *m_name;
    int m_age;
    float m_score;
public:
    Student(char *name, int age, float score);
    void show();
};
//Use initialization list
Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){
    //TODO:
}
#name(value), name1(value);

this
-this is a const pointer. Its value cannot be modified. All operations attempting to modify the pointer, such as assignment, increment, decrement, etc., are not allowed.
-this makes sense only when the object is created, so it cannot be used in static member functions.

Static static

Static static variable

static A member variable belongs to a class and does not belong to a specific object. Even if multiple objects are created, it is only a member variable static Member variables allocate an extra share of memory in addition to all objects and share it for all instantiated objects.

Static member variables must be initialized and can only be initialized outside the class. The default value is 0: type class::name = value;

int Student::name = 10;

Static static function (when will static functions be used?)

Ordinary member functions can access all members (including member variables and member functions), while static member functions can only access static members and functions.

Ordinary function members will be implicitly assigned a formal parameter this during compilation, and the address of the current object will be assigned to this. Therefore, ordinary member functions can be called after creating objects.
The compiler will not assign this pointer to static member functions, so it cannot call other ordinary member functions and variables, but only static member variables and functions.

#include <iostream>
using namespace std;

class Student{
public:
    Student(char *name, int age, float score);
    void show();
public:  //Declare static member functions
    static int getTotal();
    static float getPoints();
private:
    static int m_total;  //Total number
    static float m_points;  //Total score
private:
    char *m_name;
    int m_age;
    float m_score;
};

int Student::m_total = 0;
float Student::m_points = 0.0;

Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){
    m_total++;
    m_points += score;
}
void Student::show(){
    cout<<m_name<<"What is your age"<<m_age<<",The result is"<<m_score<<endl;
}
//Define static member functions
int Student::getTotal(){
    return m_total;
}
float Student::getPoints(){
    return m_points;
}

int main(){

    (new Student("Xiao Ming", 15, 90.6)) -> show();
    (new Student("Li Lei", 16, 80.5)) -> show();
    (new Student("Zhang Hua", 16, 99.0)) -> show();
    (new Student("Wang Kang", 14, 60.8)) -> show();

    int total = Student::getTotal();
    float points = Student::getPoints();
    cout<<"Current common"<<total<<"Students with a total score of"<<points<<",The average score is"<<points/total<<endl;

    return 0;
}

Similar to static member variables, static member functions should be added when declaring, but not when defining. Static member functions are generally called through classes (not objects).

const

const member variables and functions
Member variable

The only way to initialize const member variables is to initialize list methods.

class VLA{
private:
    const int m_len;
    int *m_arr;
public:
    VLA(int len);
};

//The initialization list must be used to initialize m_len
VLA::VLA(int len): m_len(len){
    m_arr = new int[len];
}

const constant member function

const / constant member functions can use all member variables in the class, but they cannot change their values (usually set the get function as a constant member function).

You need to add the const keyword at the end of the function header when declaring and defining.

class Student{
public:
    Student(char *name, int age, float score);
    void show();
    //Declare a constant member function
    char *getname() const;
    int getage() const;
    float getscore() const;
private:
    char *m_name;
    int m_age;
    float m_score;
};
Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){ }
void Student::show(){
    cout<<m_name<<"What is your age"<<m_age<<",The result is"<<m_score<<endl;
}
//Define constant member functions
char * Student::getname() const{
    return m_name;
}
int Student::getage() const{
    return m_age;
}
float Student::getscore() const{
    return m_score;
}

const object

Like static static, const can only call const members of the same kind (const member variables and const member functions)

character string

C style string

Essentially“\0"A character array ending with a character.

Function:

1 strcpy(s1, s2); Copy string s2 To string s1,And returns the copied content (the object returned is the former) s1)
2 strcat(s1, s2); Receive string s2 To string s1 At the end of, or directly“+"number.
3 strlen(s1); Returns the length of a string.
4 strcmp(s1, s2); if s1=s2 Return 0, s1>s2 The return value is greater than 0, s1<s2 The return value is less than 0 (the two strings are compared character by character from left to right (press ASCII Value compared to size),
Only string constants, arrays, numbers and other forms of parameters can be compared (cannot be compared).
5 strchr(s1, ch); Returns a pointer to a string s1 Chinese character ch The location of the first occurrence of.
6 strstr(s1, s2);Returns a pointer to a string s1 Medium string s2 The location of the first occurrence of.
C++Medium String The type operation method is the same as above.

String type string

  • Unlike C-style strings (char *str) and character arrays (char str[n]), string ends without "\ 0".
  • Get string length: str.length().
  • String to C-style const type string conversion (c_str()): str.c_str(), the const pointer of the returned event.
  • Subscript access is supported.

1 string splicing

String can be spliced with string, character, c-style string and character array.

2 insert string

The insert function inserts the specified string, c-style string and character array (except characters) at the specified position.

str.insert (size_t pos, const string& str);

3 delete string

erase deletes the string.

str.erase(start_pos, len);	# (starting position, deletion length). If there is no deletion length, it will be deleted to the last by default.

4 extract string

substr()

Example:
	string str = "012345";
	string s;
	s = str.substr(0, 4);
Output:
	01234

5 find string

  • find(): str.find(str1/s(char *), pos). The first parameter can be a string or C-style string. The second parameter is the location where the search starts (starting with subscript 0 by default). It returns the location where the string first appears (if the search fails, an infinite value 4294967295 is returned).
  • rfind(): generally the same as above (the second parameter here is the cut-off position).
  • find_first_of() : str.find_first_of(str1) returns the position where the same character appears for the first time in two strings. If the search fails, it returns an infinite value.

inherit

Single inheritance:
class <Subclass name>: <Inheritance type> <Parent class name>{}
Multiple inheritance:
class <Subclass name>: <Inheritance type> <Parent class name>, <Inheritance type> <Parent class name>{}

A subclass can inherit from the parent class except for the following methods:

  • Constructor, destructor and copy constructor of the parent class.
  • Overloaded operator of the parent class.
  • Friend function of the parent class.

Inheritance type

  • public: has all the level permissions of the parent class.
  • Protected: the public of the parent class will become protected of the child class.
  • Private: all permissions of the parent class will become private of the child class.

polymorphic

Polymorphic functions:

  • Through the parent class pointer, the member variables and member functions of all subclasses (including direct subclasses and indirect subclasses) can be accessed "in all directions".
  • Based on the parent class, multiple subclasses have different representations of the same member function.

Implementation method:
Add "virtual" before the member function type of the parent class.

virtual void display();

Pure virtual function

virtual Return value type function name (Function parameters) = 0;

Virtual functions with '' = 0 '' in the tail are pure virtual functions (other functions cannot). Classes containing pure virtual functions are called abstract classes and cannot be instantiated.

Polymorphic member functions are generally public,Member variables are generally**protected**. 

Not only pointers, but also references can be polymorphic. Because they cannot change references, they are less flexible.

heavy load

Overload declaration refers to a declaration with the same name as the function or method previously declared in the same scope, but their parameter list (number, type and order of parameters) and implementation are different (return type cannot be used as judgment).
overload operators
Most of the built-in operators in C + + can be redefined or overloaded,

overloaded function

Overloading of function templates
For some mixed data types, such as int, double and array, some errors will occur during the use of modulo.

Files and streams

Standard library: (fstream)
Three data types:

  • ofstream outputs a file stream, creates a file and writes information.
  • ifstream input file stream and read information from the file.
  • fstream file stream has both of and if functions.

Operating mode:

  • ios::app append mode, append all writes to the end of the file.
  • After the ios::ate file is opened, navigate to the end
  • ios::in open file for reading
  • ios::out open the file for writing (opening the file in this mode will empty the content)
  • ios::trunc if the file already exists, its contents will be truncated before opening. Set the file length to 0

Open and close files:

void open(const char *filename, ios::openmode mode);
void close();

exception handling

Header file (exception)
Syntax:

try{
    // Statements that may throw exceptions
}catch(exceptionType variable){
    // Statement handling exception
}
Example:
try{
    //Statements that may throw exceptions
}catch(exception &e){
    //Statement handling exception
}

The reason for using references in exception variables is to improve efficiency. If it is not applicable, it will go through the process of object copy (dropping the copy constructor).

If the throw exception is detected in the try, the program will immediately jump from the current position to the catch statement.

**exceptionType: * * indicates the exception type that the current catch can handle. Exception types can be basic types such as int, char, float and bool, or aggregate types such as pointer, array, string, structure and class. Exceptions thrown by the C + + language itself and functions in the standard library are exceptions of the exception class or its subclasses.
variable: used to receive exception information.

N14 automatic conversion of function arguments and formal parameters

  • Algorithm conversion: such as int to float, char to int, double to int.
  • Upward Transformation: the transformation from a derived class to a base class.
  • Const conversion: convert non const; Type to const type.
  • **Array or function pointer conversion: if the function parameter is not a reference type, the array name will be converted into an array pointer, and the function name will also be converted into a function pointer**
  • User defined type conversion.

catch in the process of converting arguments and formal parameters, the only two conversions are up conversion and array or function pointer conversion.

Exception specification
1. Exception specification of virtual function:
The exception specification of a derived class virtual function must be as strict or more strict than that of a base class virtual function.
2 exception specification and function definition and declaration:
The exception specification must be specified in the function declaration and function definition at the same time, and must be strictly consistent, not more strict or more relaxed.

Custom exception

#include <iostream>
#include <exception>
using namespace std;
 
struct MyException : public exception
{
  const char * what () const throw ()
  {
    return "C++ Exception";
  }
};
 
int main()
{
  try
  {
    throw MyException();
  }
  catch(MyException& e)
  {
    std::cout << "MyException caught" << std::endl;
    std::cout << e.what() << std::endl;
  }
  catch(std::exception& e)
  {
    //Other errors
  }
}

exception class

Dynamic memory

  • Stack: all variables declared inside the function occupy the memory of the stack.
  • Heap: unused memory in a program, which is used for dynamic allocation when the program is running.

new and delete operators
Compared with malloc, new not only allocates memory, but also creates objects.

Dynamic 2D array allocation:
int **array
// Suppose the length of the first dimension of the array is m and the length of the second dimension is n
// Dynamically allocate space
array = new int *[m];
for( int i=0; i<m; i++ )
{
    array[i] = new int [n]  ;
}
//release
for( int i=0; i<m; i++ )
{
    delete [] array[i];
}
delete [] array;

Namespace

Namespace is used as additional information to distinguish functions, classes, variables, etc. with the same name in different libraries, so as to define the context.
definition:

namespace namespace_name {
   // Code declaration
}

Call:

name::code;  // code can be a variable or a function

A namespace can be defined in several different parts, which can be composed of several separately defined parts, and each part can be scattered in multiple folders (how to use?)

Template

Parameterization of type:
In C + +, the type of data can be passed through parameters. When a function is defined, the specific data type can not be named. When a function is called, the compiler can automatically judge the data type according to the passed in arguments.
Both Value and Type can be parameterized in C + +.

Function template
Definition: a general function is established. Its data type (return value type, formal parameter type and local variable type) can be unspecified. Instead of (identifier), the virtual type is used to deduce the actual type according to the passed in arguments during function call.

Form:

templates <typename type1, type2...> return-type func-name(para list){
// Function body
}
// Type is the placeholder name of the data type used by the function (which can be used in the function definition).
// In earlier versions, typename was often replaced by class.
#include <iostream>
using namespace std;
# Exchange data values
template<typename T> void Swap(T &a, T &b){
	T temp = a;
	a = b;
	b = temp;
}

int main(){
	// Swap values of int variables
	int n1 = 100, n2 = 200;
	Swap(n1, n2);
	cout << n1 << "------" << n2 <<endl;
}

// Tempalt and typename are the keywords of the function template
// Template header: template < typename T > 

Class template

Syntax:

template<typename type1, type2...> class class-name{
// Class principal
};
template<typename T1, typenmae T2>
class Point{

private:
	T1 m_x; //x coordinate
	T2 m_y; //y coordinate

public:
	Point(T1 x, T2 y):m_x(x), m_y(y){}
public:
	T1 getX() const; // Get x coordinate
	void setX(T1 x); // Set x coordinate
	T2 getY() const; // Get y coordinate
	void setY(T2 y); // Set y coordinate
};

// When defining member functions outside the class, you still need to bring the template header
// The format is:
//Template < typename type parameter 1, typename type parameter 2,... >
//Return value type class name < type parameter 1, type parameter 2,... >:: function name (formal parameter list){
    //TODO:
}
template<typename T1, typename T2> // Template head
T1 Point<T1, T2>::getX() const /*Function header*/{
	return m_x;
}

template<typename T1, typename T2> //Template head
void Point<T1, T2>::setX(T1 x){
	m_x = x
} 

// Ibid

Creating objects using class templates

When a class template is instantiated, the data type must be explicitly specified.
When using the object pointer method, both ends of the assignment number "=" must indicate the specific data type and be consistent.

Method 1 (object variable):
Point<int, int> p1(10, 20);
Point<int, float> p2(10, 12.3);
Point<float, char*> p3(12.3, "Hello, Xiao Qi");

Mode 2 (object pointer):
Point<float, float> *p1 = new Point<float, float>(10.6, 109.3);
Point<char*, char*> *p = new Point<char*, char*>("180 degrees east longitude", "210 degrees north latitude");

Class template to implement variable length array

Argument inference of function template

As mentioned above, for ordinary functions, the type of arguments will be properly converted during function call to adapt to the type of formal parameters.
However, for function templates, type conversion is limited to const conversion and array or function pointer conversion, and when the function parameter is a reference type, the array will not be converted to a pointer.

Explicitly specify arguments for function templates:

template<typename T1, typename T2> void fun(T1 a){
	T2 b;
}
// When calling a function, use < > to specify the corresponding argument type to avoid compiler confusion.
fun<int, int>(20);

The explicitly specified template arguments match the corresponding template parameters in left to right order (the last one can be omitted).

Display materialization
1 function template

Type 2 formwork

Preprocessor

#define preprocessing

Parameter macro

#include <iostream>
using namespace std;
 
#define MIN(a,b) (a<b ? a : b)
 
int main ()
{
   int i, j;
   i = 100;
   j = 30;
   cout <<"The smaller values are:" << MIN(i, j) << endl;
 
    return 0;
}

Conditional compilation
Selectively compile part of the program source code.

#include <iostream>
using namespace std;
#define DEBUG
 
#define MIN(a,b) (((a)<(b)) ? a : b)
 
int main ()
{
   int i, j;
   i = 100;
   j = 30;
#ifdef DEBUG
   cerr <<"Trace: Inside main function" << endl;
#endif
 
#if 0
   /* This is the comment section */
   cout << MKSTR(HELLO C++) << endl;
#endif
 
   cout <<"The minimum is " << MIN(i, j) << endl;
 
#ifdef DEBUG
   cerr <<"Trace: Coming out of main function" << endl;
#endif
    return 0;
}
Output:
Trace: Inside main function
The minimum is 30
Trace: Coming out of main function

#And ## operators
"#" converts the replacement TXT token into a quoted string.
"##" is used to connect two tokens

#include <iostream>
using namespace std;

#define MKSTR(x) #x
#define concat(a, b) a ## b
int main()
{
    int xy = 100;

    cout << MKSTR(dingdingdang) << endl;
    cout << concat(x, y) << endl;
    return 0;
}
Output:
dingdingdang
100

macros predefined

  • LINE: the number of lines of the statement in which it is located.
  • FILE: the path where the current FILE is located.
  • DATE: the DATE when the source file was converted to the object code.
  • TIME: the date when the program was compiled, in the form of "hour:,minute:second"

signal processing

Signals defined in the C + + header file "< csingal >" that can be captured by the program and take appropriate actions.

  • SIGABRT: abnormal termination of the program, such as calling abort.
  • SIGFPE: incorrect arithmetic operations, such as dividing by zero or causing overflow.
  • SIGILL: detect illegal instruction.
  • SIGINT: program interrupt signal.
  • SIGSEGV: illegal access to memory.
  • SIGTERM: the termination request sent to the program.

Capture signal:

	signal(registered signal, signal handler)

Where registered represents the captured signal number (an integer), and signal is a pointer to the signal processing function.

Send signal:

int raise (signal sig);
// sig is SIGINT, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM and sigup

Multithreading

STL

Topics: C C++