c + + introductory tutorial

Keywords: C++

01 introduction

Connection between the two:
C + + is a superset of C.
Compilers that support the C + + language must support the C language.

Differences between the two:
C language supports process oriented structured design method. (fortran)
C + + language supports object-oriented design method.
The standard template library STL makes the C + + language more convenient to use and supports generic programming methods. (Java,python)

Process oriented (structured programming method)

Top down, gradual refinement. Module decomposition and function abstraction are adopted to divide and rule from top to bottom.

Top down, gradual refinement and modularization.

object-oriented

Object oriented method is a method to construct, test and reconstruct software by using the concepts of object, class, encapsulation, inheritance and polymorphism.

The relationship between program modules is simpler, and the independence of program modules and the security of data are well guaranteed.
Through inheritance and polymorphism, the reusability of the program can be greatly improved, which makes the software development and maintenance more convenient.

Objects: properties (data), behaviors (functions)

Classes: Abstract

It ties data and the process (function) of operating data together to form an interdependent and inseparable whole (i.e. object)

High module independence
High code reusability;
Good scalability
Good maintainability

In principle, data in similar objects can only be processed by the methods (member functions) provided by this class. Class separates the interface from the implementation through encapsulation, and connects with the outside world through the interface. Objects communicate through messages.

A collection of a set of objects with the same properties and services
It provides an abstract description of all objects belonging to this class, including two main parts: attribute and behavior.

Encapsulation (private, public)

Meaning 1: combine all attributes and services of the object to form an indivisible independent unit (i.e. object)
Meaning 2: information concealment. That is, the internal details of the hidden object form a boundary to the outside, and only a limited external interface and external contact are retained.

Advantages of packaging:
1. Reduce the coupling between components and improve the independence of components
2. With concealment and security (such as bank account)
3. Easy to maintain (due to independent data, it is easy to find problems)
4. Encapsulation separates the user of the object from the designer. The user only needs to access the object through the interface without understanding the internal details of the object, which improves software reuse.
Disadvantages of encapsulation:
More input and output functions are required.

inherit

Inheritance: the intersecting relationship between classes, so that one class of objects can inherit the characteristics and functions of another class of objects.
Features with inheritance relationship between classes:
Shared features among classes (including sharing of data and program code): heredity
Slight differences or new parts between classes (including unshared program code and data): variation
There is a hierarchy between classes (just as human beings form a family relationship through inheritance)

It effectively improves the reusability of the program and reduces the redundancy of the program code.
It enhances the consistency of the program, reduces the interface and interface between program modules, and makes the program easier to maintain.
Inheritance is a powerful tool for automatically propagating program code.
Inheritance is an effective means to construct, establish and expand new classes.
Inheritance is transitive
If class C inherits class B and class B inherits class A, class C inherits class A

polymorphic

Cast polymorphism (CAST)

Overload polymorphism (function overload, operator overload)

Contains polymorphic (virtual function)

Type parameterization polymorphism (function template, class template)

Polymorphism refers to the attribute or behavior defined in a general class. After being inherited by a special class, it can have different data types or show different behaviors. This makes the same attribute or behavior have different semantics in general classes and their special classes.

02 simple programming

Variable storage type

Dynamic temporary variable

It belongs to temporary storage, and its storage space can be overwritten and used by several variables for many times.

auto

Default (usually omitted)

(in the new C + + standard, it represents the type automatically deduced by the compiler)
Static (static variable)
It is stored in memory at a fixed address and is valid throughout the running of the program.
register
Stored in the general register.
extern
Use variables defined in another file

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG uwfswdqm-1631360818264) (C: \ users \ Dell \ appdata \ roaming \ typora \ typora user images \ image-2020122172236982. PNG)]

C + + uses new and delete to request and free memory.
new and delete are not functions, but operators.
Using new to apply for memory space can be a unit or a group of units.
The delete operator frees the requested memory space.

char* char_ptr = new char;
int* int_array = new int[20];  
Mixed* m1 = new Mixed(1,1,2);
*char_ptr = 'a';

delete char_ptr;
delete[] int_array;
delete m1;

typedef statement

Give an existing data type another name

typedef  Existing type name new type name table;

Enumeration type

enum  Enumeration type name  {Constant list};

Enumeration type Application Description:

Enumeration elements have default values, which are:
0,1,2,...
You can also specify the value of enumeration elements when declaring, such as:

enum Weekday { SUN=7,MON=1,TUE,WED,THU,FRI,SAT };

Enumeration elements are constants and cannot be assigned values.
For example, cannot write: SUN = 0;
Cast is required when assigning an integer value to an enumerated variable.

Weekday w = (Weekday)5;

Enumeration values can be used for relational operations.

< >= <= == !=

int count;
for (count = WIN; count <= CANCEL; count++) 
    //++Is an int operation, implicit type conversion
    {   
    	result = (game_result)count;
     	// Explicit type conversion
        if (result == omit)
        {   
            cout << "The game was cancelled\n";
        }
        else
        {   
            cout << "The game was played ";
            if (result == WIN)    cout << "and we won!";
            if (result == LOSE)   cout << "and we lost.";
            cout << "\n";
        }
    }

>> // Extractor
<< // Inserter
//File reading

ifstream sifile("a.txt");

sifile >> ......
    
sifile.close();

ofstream sofile("b.txt");

sofile << ......;

sofile.close();

03 function

Formal parameters are initialized internal dynamic variables,
Longevity and visibility are limited to functions

Type identifier function name (formal parameter table)                      
{  
   Statement sequence
}

Function parameter passing: pass value, pointer and reference

Pass parameter values:

Passing parameter values is also called value passing.
When the function is called, the argument value is copied to the formal parameter value.
Value passing belongs to one-way passing, and the argument cannot be changed

Pass parameter pointer

Passing parameter pointer is also called passing pointer and pointer passing.
"Pointer passing" is actually the address value of the passed variable.
When the parameter is called, the address of the argument is copied as the pointer variable of the formal parameter.
Pointer passing can change the value of the argument.

Pass parameter reference

A Reference is an alias, which is another name of an object. The main purpose of a Reference is to describe the parameters and return values of a function. Especially for overloading operators.
Grammatical form

type &  Reference name=Variable name;

//Both are correct:
int &ri = i;
int& ri = i;

// It is equivalent that ri is an alias of i. changing ri or i is equivalent to changing the same quantity

The reference is not a value and does not take up additional storage memory space

int i=9;
int& ir=i;

References must be initialized when declared

Moreover, once the reference is initialized, it cannot be changed to point to other objects.

int& ir;//error

The initial value of a reference can be a variable or another reference, and the type is consistent.

	int i=9;
   	int& ir=i;
	int& ir1=ir;
	float f=2;
	int& ir3=f;  //error

Can have a pointer reference, can not have a referenced pointer

int  b=1;
int* p=&b;
(int*)& rp=p;  //rp is a reference that refers to a pointer
(int&)* ra=a;  //error

You cannot create a reference to an array. You can create a reference to an array element

int  a[10];
int& ra[10]=a;  //error
int&  ra=a[8];  //ok

Passing parameter references is also called passing references.
The passed reference is actually the alias of the passed variable, and the formal parameter is the alias of the argument.
When the parameter is called, the argument and the formal parameter share the memory unit of the argument, and no copy action occurs.
Passing a reference can change the value of an argument.
Passing references improves the efficiency of function execution.

For example:

void fun(int& x, int& y);

Functions that use the keyword inline are called inline functions.

At compile time, replace with the function body at the call

inline double calArea(double radius) 
{  
	return PI * radius * radius;
}
Normal function call procedure:

Push the return address onto the stack
Push parameters onto stack
Execution function body
Free parameter temporary space
Jump back to function call location

Functions of inline functions:

In the program source file, keep the modularization of function and the structure of program - function
In the binary executable file of the program (during program operation) - the function module is removed, and it is directly a statement block

When an inline function is compiled, it is replaced with the function body at the call.
It reduces the cost of parameter passing and control transfer of runtime function calls.
Improve operation efficiency.

The inline function has a clear definition of the parameters and return values of the function, which enhances the security of the code. The macro definition does not.
The parameters and return values of the inline function have clear type identification, and the macro definition does not.

The keyword inline must be placed with the function definition body to make the function inline. Only placing inline in front of the function declaration does not play any role.

Functions with relatively simple function body and frequently called functions are suitable to be defined as inline functions.
Loop statements and switch statements cannot exist in an inline function body.
Inline functions cannot be defined as recursive functions.

The compiler determines whether a function is inline.
inline is a keyword for implementation, not for declaration.
inline is only a request (recommendation) to the compiler, which can be rejected by the compiler.
Modern C + + compilers optimize the code, and non inline functions may also be inlined.
Inlining comes at the cost of code inflation.
When the inline function changes, all files calling the inline function need to be recompiled.

Default parameter value

The default formal parameter value can be given in advance when a function is declared. If an argument is given when calling, the actual parameter value will be used. Otherwise, the default formal parameter value given in advance will be used.

Formal parameters with default parameters must be at the end of the formal parameter list, that is, there cannot be parameters without default values to the right of the default formal parameter value. Because the combination of real participation formal parameters at call time is in the order from left to right.

int add(int x, int y = 5, int z = 6);//correct
int add(int x = 1, int y = 5, int z);//error
int add(int x = 1, int y, int z = 6);//error

If a function has a prototype declaration and the prototype declaration is defined before, the default formal parameter value must be given in the function prototype declaration.

There is already a function declaration. The default parameter value will not be specified when defining.

If only the function is defined or the function is defined first, the default formal parameter value should be given in the function definition.

In the same scope, the description of the default parameter value should remain unique, but if in different scopes, it is allowed to describe different default parameters.

overloaded function

C + + allows functions with similar functions to be declared with the same function name in the same scope, resulting in overloading.

//Different parameter types
int add(int x, int y);
float add(float x, float y);

//Different number of formal parameters
int add(int x, int y);
int add(int x, int y, int z);

Single interface, multi implementation

In C + +, you can provide two or more functions with the same name and the same function, as long as the parameter table of each function is unique (the number of parameters, parameter type, or parameter order are different).
The compiler will choose which function to call according to the best match between the type and number of arguments and formal parameters.

Overloaded functions cannot be distinguished only by different return types and formal parameter names

In the case of implicit type conversion of overloaded function parameters, overloaded functions have ambiguity when called.
At this point, the function call must be completed using an explicit cast.

#include <iostream>
void print(double a) {
	cout << "print_d  " << a << endl;
}
void print(long a) {
	cout << "print_l " << a << endl;
}
int main(void) {
    int a;
    print(a); //error
    print(double(a));
    print(long(a));
    return 0;
}

Ambiguity sometimes occurs when it is both an overloaded function and a function with default parameters.

int maximum(int x, int y, int z = 10) 
{   
    int max = x;
    if (y > max) max = y;
    if (z > max) max = z;
    return max;
}
int maximum(int x, int y) 
{    
    int max = x;
    if (y > max) max = y;
    return max;
}

//Calling the following will produce ambiguity
maximum(a,b);

04 classes and objects

① The access qualifiers private, public and protected in the class declaration have no order
② In a class, there is no limit on the number of occurrences of access qualifiers private, public and protected
③ Both data members and function members can be set to public, private or protected properties.
For the purpose of information hiding, data members are often set to private permissions
Set the member function that needs to be accessed by the external function of the class (not the function defined by this class) to public permission.

④ If the access qualifier is not explicitly written out, the default member has private access.
⑤ Data members can be any data type
Such as integer, floating point, character, array, pointer, reference, etc
It can also be an object of another class or a pointer to an object
It can also be a pointer to its own class
But it cannot be an object of its own class.
In addition, data members cannot be specified as * * auto, register and extern al) * * storage types.

class B {
private:
int a;
A  obja1;
A  *obja2;
B  *objb;
B  b1;	// X
auto b;		// X
extern int c;	// X
register int d;	// X
public:
......
};

auto has two meanings

When declaring a variable, the type of the variable is automatically inferred according to the initialization expression, and the placeholder of the function return value when declaring a function.

Function implementation outside class declaration

<type>  <Class name> ::<Function name>(<Parameter table>)
{<Function body>}

Inline function

In order to improve the efficiency of runtime, simpler functions can be declared as inline.
The function is to reduce the number of actual function calls and the cost of function calls
Do not have complex structures (such as loop statements and switch statements) in the body of inline functions.
How to declare inline member functions in a class: put the function body in the declaration of the class and use the inline keyword.

class Point
{
public:
    void Init(int initX,int initY);
    int GetX();
    int GetY();
private:
    int X, Y;
};
inline void Point::Init(int initX,int initY)
{ 
    X = initX;
 	Y = initY;
}
inline int Point::GetX()
{  
    return X;
}
inline int Point::GetY()
{  
    return Y;
}

Default parameter value

Class member functions can also default parameter values, and the calling rules are the same as ordinary functions.
The default value of a class member function must be written in the class declaration, not in the function implementation outside the class declaration.

class Clock {
public:
void setTime(int newH = 0, int newM = 0, int newS = 0);
...
};

this pointer

this is an implicit pointer in the member function to the current object itself (i.e. the first address of the class object to which the member function belongs)

class X
{		......
		f(...)
};
		
X::f (......)
{
		this->member
}

Compiler's handling of this pointer

① The compiler changes the definition of class members and redefines each class member function with an additional this pointer

② The compiler changes the call of each class member function, plus an additional argument, that is, the address of the called object

Two common applications of this pointer

Use this pointer to distinguish ambiguities

Use the this pointer to return the calling object

Clock& Clock::SetHour(int NewH)
{
    Hour = NewH;
	return *this;
}

private

The outside world is inaccessible
It can be accessed arbitrarily inside the class

Inside the class is "within the scope of definition"
Including: curly brackets {}; Class and class qualified operators

Outside the class, only indirect access is allowed. It can only be accessed through the object's interface - member function with public attributes

protect

When there is only one class, the access permissions are the same as private
Class can be accessed arbitrarily
Outside the class, only indirect access is allowed. It can only be accessed through the object's interface - member function with public attributes
In a derived class, it has private or protected access properties
Unlike private components, they are not accessible in derived classes

Similarities and differences between private and protected

In a separate class, both private and protected data can only be accessed directly in the class definition; Data of both private and protected types cannot be accessed directly outside the class definition
In the class family with inheritance relationship, the private data of the parent class cannot be accessed directly in the child class; The protected data of the parent class can be accessed directly in the child class

Relationship between object and class

The relationship between object and class is the relationship between variable and variable type. Object is an instance of class.

Pointer to object

Clock clock1;
Clock *ptr=&clock1;

Clock *ptr2 = new Clock;
...
delete ptr2;

Clock clock[10];	// Pointer to object array
Clock *clock1 = new Clock[10];
...
delete[] clock1;

Clock * clock[10];	// Object
for(int i=0;i<10;i++)
	clock[i] = new Clock;
...
for(int i=0;i<10;i++)
	delete clock[i];

Object Assignment

Two objects must be of the same type;
Copy the values of data members. After assignment, the two are irrelevant;
If the object has pointer data members, assignment may cause problems; (if there is a problem with shallow copy, you must use deep copy)

Class 05 and object 2

Constructor

class X{
    ......
    X(...);`// Constructor
    ......
} 

Constructor has the same name as the class.
Constructor has no return type.
Constructors can be overloaded.
Constructors are automatically called by the system and are not allowed to be explicitly called in programs.

It can only be called automatically by the system when defining objects!
Call form: class name, object name (parameter table);
The system will call a constructor according to the parameter table
If there is no parameter table, the default constructor is called.

Programmers are not allowed to display the name of the calling constructor in the program. It is not allowed at any time!

① Constructors cannot have return types, even void.

② Constructors are automatically called by the system and cannot be explicitly called in a program.

Person wang;		//Call constructor
Wang.Person("WangWei",20);	//error

③ The call time of the constructor is the first time after the object is defined, that is, the constructor is the first function called by the object.

④ The constructor is also called when defining an object array or creating a dynamic object with new. At this time, there is no need to have a variable name, but when defining an array object, there must usually be a constructor without parameters

⑤ Constructors should usually be defined as public members, because when defining objects in a program, the call of constructors is involved. Although it is an implicit call by the compilation system, it is also a member function access outside the class.

Nonparametric structure

1. System default constructor
C + + stipulates that each class must have a constructor. If a class does not define any constructor, the compiler will generate a default constructor for it.

class X {
    X(){}    //The system default constructor is similar to this
    ......
}

When creating an object with the default constructor, if the created class is a global object or a static object, all data members of the object are initialized to 0; If a local object is created, the object data member is not initialized.

point p1;	// overall situation
int main() 
{  
    static point p2;	//Static local
	point p3;	local
    return 0;
}

The default constructor is generated only when the class does not define any constructor.
Once any form of constructor is defined, the system no longer generates a default constructor.

2. Overloaded parameterless constructor

The default parameterless constructor generated by the system does not actually initialize the data members of the object.
C + + allows you to explicitly define a parameterless constructor so that you can provide initial values for the data members of an object.
Sometimes, in order for the class to work properly, it is necessary to provide a parameterless constructor.

Default formal parameter constructor

When the values of data members are fixed, they can be initialized by providing default values for the parameters of the constructor.

overloaded constructor

Using the constructor of the default formal parameter value, combine the above constructors into one

Forced type conversion is performed automatically

copy constructor

class X{
public:
    ......
    X(const X&);     //Common prototypes of copy constructors
}

When a class has data members of pointer type, the default copy constructor often causes pointer hanging problems.

(1) The copy constructor is the same as the general constructor, has the same name as the class, and has no return type.
(2) The parameters of a copy constructor are often references to objects of type const.
(3) In most cases, the default copy constructor can copy and create objects. However, when a class has data members of pointer type, the default copy constructor may cause pointer hanging problems, and an explicit copy constructor needs to be provided.
(4) Calls to the copy constructor are often made outside the class and should be specified as a public member of the class.

Copy function call

Case 1: call copy constructor

Case 2: the copy constructor is called when the object is used as the function parameter

Case 3: the copy constructor is called when the object is used as the return value of the function

Solve the pointer suspension problem

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ti7qwpnc-1631360818273) (C: \ users \ Dell \ appdata \ roaming \ typora \ typora user images \ image-20201218175105355. PNG)]

Person::Person(const Person &p) 
{  
    name = new char[strlen(p.name) + 1];
	strcpy_s(name, strlen(p.name)+1, p.name);
	age = p.age;
}
//First allocate a new space, and then copy the contents of the string

Initialization list

Constructor name(Parameter table): Member 1(Initial value 1),Member 2(Initial value 2),...
{
......
}

The content between the ": after the parameter table and the function body {...} is the member initialization list. The meaning is to assign the value of the initial value parameter in the bracket to the member before the bracket

① Members in the constructor initialization list are initialized in the same order as they are declared in the class, regardless of the order in the initial list. For example, for the class in example 3-10, the following three constructors are identical.

Tdate::Tdate(int m,int d,int y):month(m),day(d),year(y){}
Tdate::Tdate(int m,int d,int y):year(y),month(m),day(d){}
Tdate::Tdate(int m,int d,int y):day(d),year(y),month(m){}

Although the order of month, day and year in the initialization list of the three constructors is different, they are initialized in the order of month → day → year, which is the declaration order in Tdate.

② The constructor initialization list is executed before the statement in the constructor body.
③ Constant members, reference members, class object members, derived class constructors, and calls to the base class constructor must be initialized with an initialization list.

Destructor

class X
{
	~X ( ) {......};
}

The function name is ~ class name
No parameters
No return value
Cannot overload: there is only one destructor per class

Destructor call timing

Called automatically at the end of the object's lifetime
For example: Point* p = new Point;
delete p;
Local object: the end of a defined statement block
{

​ Point p;
......
}
Global objects: at the end of the program
Static object: at the end of the program

① If more than one object ends its lifetime at the same time, C + + will call the destructor in the reverse order of calling the constructor.
② Each class should have a destructor, if not explicitly defined. C + + will produce a minimized default destructor.
③ Both constructors and destructors can be inline functions
④ Under normal circumstances, both destructors and constructors should be set as public members of the class. Although they can only be called automatically by the system, these calls are made outside the class.

06 classes and objects 3

Create objects every time: first construct sub objects, and finally construct member variables.

It is not only responsible for assigning initial values to the basic type member data in this class, but also initializing the child object members.

Child objects must be constructed using an initialization list.

Class name::Class name(The formal parameters required by child object members, and the formal parameters of this class member):Sub object 1(parameter),Sub object 2(parameter),......
{  
           Initialization of this class  
}

① Calling order of combined class constructor: call the constructor of child objects first (according to the declaration order during combination, the declarant first constructs first). And then call the constructor of this class.

② Destructors are called in reverse order.

③ The composite class constructor initializes the child object that does not appear in the list, and initializes with the default constructor (parameterless constructor) of the child object.

④ In the default constructor of the composite class automatically generated by the system, all sub objects are initialized with the default constructor (parameterless constructor) of the sub object.

Line::Line(Point xp1, Point xp2): p1(xp1),p2(xp2)
{  
    cout << "Calling constructor of Line" << endl;
	double x = (double)p1.getX() - (double)p2.getX();
	double y = (double)p1.getY() - (double)p2.getY();
	len = sqrt(x*x + y*y);
}

Line::Line(Point xp1, Point xp2): p1(xp1),p2(xp2)
{  
    cout << "Calling constructor of Line" << endl;
	double x = (double)p1.getX() - (double)p2.getX();
	double y = (double)p1.getY() - (double)p2.getY();
	len = sqrt(x*x + y*y);
}

int main()
{  
    Point myp1(1, 1), myp2(4, 5);
	Line line(myp1, myp2);
	return 0;
}

Operation results

Calling the copy constructor of Point copy constructor parameter xp1
Calling the copy constructor of Point copy constructor parameter xp2
Calling the copy constructor of Point p1
Calling the copy constructor of Point p2
Calling constructor of Line constructor

Line::Line(Line& l): p1(l.p1), p2(l.p2)
{  
    cout << "Calling copy constructor of Line" << endl;
	len = l.len;
}

Operation results

Calling the copy constructor of Point line2.p1
Calling the copy constructor of Point line2.p2
Calling copy constructor of Line2

Constructor of composite class

//Constructor of composite class
Line::Line(int x1,int y1,int x2,int y2): p1(x1,y1),p2(x2,y2)
{  cout << "Calling constructor of Line" << endl;
double x = (double)p1.getX() - (double)p2.getX();
double y = (double)p1.getY() - (double)p2.getY();
len = sqrt(x*x + y*y);
}

int main()
{  int myx1(1), myy1(1),myx2(4), myy2(5);
Line line(myx1,myy1,myx2,myy2);
return 0;
}

Operation results

Calling constructor of Line creates two new points and constructs a line

Functions in child objects can be accessed directly

void Line::setP1(int xx, int yy)
{  
    p1.setX(xx);
	p1.setY(yy);
}

Forward reference declaration

Class should be declared before use
If you need to reference a class before its declaration, you should make a forward reference declaration:
class B;
The forward reference declaration introduces only one identifier for the program, but the specific declaration is elsewhere.

// X
class A
{public:
   void f(B b); 
};
class B
{public:
   void g(A a);
};

// √
class B; //Forward reference declaration
class A
{
public:
   void f(B b);	//There can only be definitions. The specific function body needs to be defined after class B
};
class B
{
public:
   void g(A a);
};

void A::f(B b)
{ 
    m_a = b.get();
}

For the actual use of class B, after the complete declaration (or definition) of class B.

Although the forward reference declaration is used, the object of the class cannot be declared or used in inline member functions until a complete class declaration is provided.

class Fred; 		//Forward reference declaration
class Barney
{   
    Fred x; //The declaration of class Fred is not perfect		
    Fred &x; 	//After forward reference declaration, you can declare the reference and pointer of Fred class object.
    x.method(); 	//10. Fred's member function cannot be called
};

Only class Fred is declared forward and class Fred is not defined.

Fred's object cannot be declared

Cannot use Fred's object (call Fred member function).

Only Fred's function parameters, references and pointers can be declared.

07 data sharing and protection

Scope

from small to large

① Function prototype (Declaration of function prototype only)

Its scope starts at '(' and ends at ')'.

The scope of formal parameters is only between () and cannot be used in other parts of the program body, so they are optional.

② Block scope (local scope)

A block is a program unit enclosed in curly braces.

An identifier declared in a block whose scope begins at the declaration and ends at the end of the block.

A formal parameter of a function, an identifier declared in a block, with a block (local) scope. Its scope starts from the declaration and is limited to functions and blocks.

③ Class scope

If a local scope identifier with the same name is not declared in the member function of X, the member m
Accessed through the expression x.m or X:: M. x: : m is the way static members or static functions are accessed
Through the expression PTR - > m

④ Namespace namespace

Global namespace: the default namespace
Anonymous namespace: unique to each source file

A namespace defines a namespace scope
Use identifiers from other namespace scopes
Namespace name:: identifier name
Example: declare an object of SomeClass type

SomeNs::SomeClass obj1;

Expose identifiers of other namespace scopes to the current scope

For all identifiers:
using namespace namespace name;

For a specific identifier:
using namespace name:: identifier name;

⑤ File scope

Flags not defined in the preceding domain
Also known as: global variable
Can be used throughout the file

visibility

Flags are not always visible within their scope
Because the scope is nested, if a variable with the same name is defined in the inner scope, the variable with the same name in the outer layer will not be visible in the inner layer

Identifier should be declared first and referenced later.
If an identifier is declared in the outer layer and there is no declaration of an identifier with the same name in the inner layer, the identifier is visible in the inner layer.
For two nested scopes, if an identifier with the same name as that in the outer scope is declared in the inner scope, the identifier of the outer scope is not visible in the inner scope.

Object name, function name and enumeration constant name in the same scope will hide the object name, class name or enumeration type name with the same name.
Overloaded functions can have the same function name.

Use scope qualifier:

Use invisible global variables in the inner layer

Survival period

Static lifetime:

Global variables (variable definition - > program end)

static variable (variable definition - > program end) (program modularization and data sharing)

Dynamic survival

Objects declared in the block scope without static modification are dynamic lifetime objects (commonly known as local lifetime objects).
It starts when the program executes to the declaration point and ends at the end of the scope that names the identifier.

Static member

Static data member

Declare with keyword static
All objects of this class maintain the same copy of this member
Must be defined and initialized outside the class. Use (::) to indicate the class to which it belongs.

Static data members are not created by constructors
Is created by a variable definition statement:

static int count;
int Point::count = 0;

Each object of the class has its own data member independently;
But the entire class has only one static data member
(the entire class also has only one member function)

Static members are shared by all objects of a class
(member functions are also shared by all objects)

Static member function

Out of class code can use class names and scope operators to call static member functions.
No this pointer
Static member functions can only reference static data members or static member functions that belong to this class.

The keyword static is used for declaration and not for definition

Access to static members of public:
You can use the class Point::showCount(); You can also use any object a.showCount();

Access to ordinary members requires the current object (* this)
The current object is not required for access to static members

Differences between static member functions and ordinary (non static) member functions:
Ordinary member functions have this pointer
The static member function does not have a this pointer

class Point
{public:
Point(int xx=0,int yy=0):x(xx),y(yy) 
{ count++; }	// Create a new point and the counter will increase automatically
Point(Point &p);
int getX() 
{  return x; }
int getY() 
{ return y; }
void showCount()
{  cout<<" Object count="<<count<<endl; }
private:
   int x, y;
static int count;	// statement
};
Point::Point(Point &p)
{  x = p.x;
y = p.y;
count++;	// Create a new point and the counter will increase automatically
}
int Point::count = 0;	//Out of class initialization

For non static member functions, the compiler changes its call and adds an additional argument, the address of the called object.

For calls to static member functions, this additional argument is not added. (the static function has no this parameter)

There is no current object in the static member function, so there is no this pointer

Conclusion:

Static member functions access non static data members through objects

Access to static members does not need to pass through objects

class A
{
    public:
	static void f(A a);
	private:
	int x;
};
void A::f(A a)
{  
    cout << x;	//X
	cout << a.x;	//√
}

friend function

Friend function is a non member function modified by the keyword friend in the class declaration. private and protected members can be accessed through the object name in its function body
Function: increase flexibility, so that programmers can make reasonable choices in encapsulation and rapidity.

The friend function of a class can directly access all members of the class, including members of public, protected and private types.

The friend function does not need to call the member function of the class repeatedly, and the efficiency is high.

class X
{
    ......
    friend  T  f(...);         //Declare f as a friend function of class X
    ......
};
......
T  f(...) { ...... }          //Friend is not a class member function, so you cannot use "X::f" to qualify the function name when defining
friend float dist(Point& a, Point& b);	// Intra class declaration

float dist(Point& a, Point& b) // definition
{  
    double x = a.x - b.x;
	double y = a.y - b.y;
	return static_cast<float>(sqrt(x*x+y*y));
}

Friend class

If a class is a friend of another class, all member functions of this class can access the private or protected members of the other class.
Declaration syntax: use the friend modifier to describe the friend class name in another class.

class A
{ 
    friend class B;
public:
  void display()
  {  
      cout<<x<<endl;
  }
private:
  int x;
}



class B
{
public:
  void set(A& a,int i);	// Object a in class A is a function parameter
  void display(const A& a);
};
void B::set(A& a,int i)
{   
    a.x=i;	// Direct access to a's private data
}
void B::display(const A& a)
{	
    cout<<a.x<<endl;
}

// A B can have more than one A. B can directly access the private of a and protect members. A and B are two independent classes.

// OR

class B
{
public:
  void set(int i);
  void display();
private:
  A a;	// Object a in class A is directly a private member
};
void B::set(int i)
{   
    a.x=i;	// Direct access to a's private data
}
void B::display()
{   
    cout<<a.x<<endl;
}

// In this design, A is A child of B, and A B has and can only have one A
Characteristics of friend relationship
Unidirectional

If class B is declared as a friend of class A, the member function of class B can access the private and protected data of class A, but the member function of class a cannot access the private and protected data of class B.

Non transitive

If class C is declared as a friend of class B and class B is a friend of class A, class C cannot be considered as a friend of class A.

Not inherited

If class B is declared as a friend of class A and class C is a subclass of class A, class B cannot be considered as a friend of class C.

As long as there is no "friend class B;" statement, there is no friend relationship

Protection of shared data

Objects of constant type must be initialized and cannot be updated.

Constant object: must be initialized and cannot be updated.

const Class name object name 
Class name const Object name 

Constant reference: referenced objects cannot be updated.

const  type specifier   & Reference name

Constant group: array elements cannot be updated.

type specifier   const  Array name[size] = {Initial value list};

Constant pointer: a pointer to a constant

const type specifier  * Pointer name = &constant;  	//pointer to const 
const type specifier  * const Pointer name = &constant; //Constant pointer to constant

Constant data member
The data member described using const.
Constant member function
Functions described with const keyword -- member functions that do not update member data.

Constant data member

A constant object can only call constant member functions.
Ordinary ("extraordinary") objects call ordinary ("extraordinary") functions;
Ordinary objects can also call constant functions.

Constant data members are initialized as initialization lists

#include <iostream>
using namespace std;
class A
{public:
   A(int i);
void print() const;
private:
const int a;
static const int b;
};

const int A::b = 10; 	// Static variable initialization
A::A(int i):a(i)	// Constant data members are initialized in the form of an initialization list and cannot be assigned by =
{ }

Constant member function

Constant member functions do not update the data members of an object.

Description format

Type specifier function name (parameter table) const;

Here, const is a component of the function type, so the const keyword should also be carried in the implementation part.

const can be used for function overloading

The const function passes the const this pointer

Ordinary member functions pass the (variable) this pointer

A constant member function can only call a constant member function

Often referred to as formal parameter const&

Type specifier function name( const type&);

effect:
Improve the efficiency of passing parameters when calling functions -- passing references&
Functions are not allowed to change arguments -- protect arguments

Store the results through temporary variables, do not change the incoming things, and finally return temporary variables.

Multi file structure and compilation preprocessing commands

#include contains instructions
Embed a source file at this point in the current source file.
#Include < file name >
Search in the standard way. The files are located in the include subdirectory of the C + + system directory
#include "file name"
First, search in the current directory. If not, search in the standard way.
#define macro definition directive
Defining symbolic constants has been replaced by const definition statements in many cases.
Defines a macro with parameters, which has been replaced by an inline function.
#undef
Delete the macro defined by #define so that it no longer works.

#if constant expression 1
    Program body 1  //Compile when constant expression 1 is non-zero
#elif constant expression 2
    Program body 2  //Compile when constant expression 2 is non-zero
#else
    Program body 3  //Compile in other cases
#endif
        
#ifndef identifier
   Segment 1
#else
   Segment 2
#endif
 If the identifier is not defined, compile segment 1, otherwise compile segment 2.
        

09 class inheritance and derivation

The process of constructing a new class while maintaining the characteristics of an existing class is called inheritance.
The process of creating a new class by adding its own features to an existing class is called derivation.
The inherited existing class is called the base class (or parent class, superclass).
The derived new class is called a derived class (or subclass).

The purpose of inheritance: code reuse.

Define a new class based on the existing class, that is, the data member and member function of the base class.

Inheritance purpose
code reuse
Descriptive ability: generic relationships exist widely

Definition of derived classes

Inheritance method: private, protected, public

Newly added components in derived classes: data members, member functions

class Derived class name: inheritance mode base class name
{
        Member declaration;
};

Generation process of derived classes

  1. Absorbing base class members
  2. Transform base class members
    Change the access properties of base class members in derived classes
    Redefine base class function (same function name, same parameter name)
    Overloaded base class function (same function name, different parameter names)
  3. Add new member
A derived class cannot inherit the following from a base class

Constructor and destructor of base class
Friend function of base class
Static data members and static member functions

Memory layout

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kpekmept-1631360818277) (C: \ users \ Dell \ appdata \ roaming \ typora \ typera user images \ image-20201221170127896. PNG)]

Inheritance mode

Public, private, protection

Different inheritance methods will affect the access rights of base class members in derived classes to varying degrees.
The default inheritance method of class is private inheritance

Protect members

protected member in base class
Class internals: accessible
Consumer of class: cannot access
Class: can access

Characteristics and functions of protected members
For the class and derived class that create it, it has the same properties as public members.
For the users of the class, it has the same nature as private members.
It not only realizes data hiding, but also facilitates inheritance and code reuse.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ly6bguc5-1631360818280) (C: \ users \ Dell \ appdata \ roaming \ typora \ typora user images \ image-20201221203028421. PNG)]

public inheritance

The access properties of the public and protected members of the base class remain unchanged in the derived class, but the private members of the base class cannot be accessed directly.

Member functions in derived classes can directly access public and protected members in the base class, but cannot directly access private members of the base class.

In the main() function, only public members of the base class can be accessed through objects of derived classes

Private inheritance

public and protected members can be accessed in derived classes

public member in base class cannot be accessed in main()

Protect inheritance

Both the public and protected members of the base class appear in the derived class as protected, but the private members of the base class cannot be accessed directly.
Member functions in derived classes can directly access public and protected members in the base class, but cannot directly access private members of the base class.
Objects that pass through a derived class cannot directly access any members in the base class

Type compatibility rule (public inheritance only)

1. The object of the derived class can be assigned to the base class object.

Derived d;
Base b = d;

2. Assign the address of the derived class object to the base class pointer.

Derived d;
Base *b = &d;

3. Initialize the reference of the base class object with the derived class object.

Derived d;
Base &b = d;

In the constructor of a derived class, the constructor of the base class can be used for initialization.

No matter which way you assign a derived class object to a base class object, you can only access the members of the base class object part of the derived class object, not the custom members of the derived class.

Multiple inheritance
class Derived class name:Inheritance method 1 base class name 1,Inheritance mode 2 base class name 2, ...
{
        Member declaration;
};
Constructor on inheritance

The constructor of the base class is not inherited, and the derived class needs to declare its own constructor.

When defining a constructor, you only need to initialize the new members in this class. The initialization of inherited base class members is automatically completed by calling the base class constructor (default).

C::C()
//Equivalent to
C::C():B()

(automatically call the base class constructor using the initialization list)

The constructor of the derived class needs to pass parameters to the constructor of the base class

Derived class name::Derived class name(Formal parameters required by the base class,Formal parameters required by members of this class):Base class name(Parameter table)
{
	Initializing assignment statements for members of this class;
};

When a default constructor or an undeclared constructor is declared in the base class, the derived class constructor may or may not pass parameters to the base class constructor. Construct an object of a derived class

The default constructor of the base class will be called.

When the constructor with formal parameters in the base class needs to be executed to initialize the base class data, the derived class constructor should provide parameters for the base class constructor in the initialization list.

Derived class name::Derived class name(Formal parameter table):Base class name 1(parameter),Base class name 2(parameter), ...Base class name n(parameter),
						Initialization of embedded objects
{
        Initializing assignment statements for members of this class;
};

1. Call the base class constructor in the order declared when they are inherited (from left to right).

2. Initialize embedded objects in the order they are declared in the class.

3. Execute the contents of the constructor body of the derived class.

Ancestor (base class)
Re guest (member object)
After oneself

class Derived: public Base2,public Base1,public Base3
{public:
Derived(int a,int b,int c,int d):Base1(a),member2(d),member1(c),Base2(b)
{ }
private:    //Embedded member object of derived class
    Base1 member1;
    Base2 member2;
    Base3 member3;
};

base2 base1 base3 member2 member1 member2 member3

If a copy constructor is not written when creating a derived class object, the compiler generates an implicit copy constructor.

This function first calls the copy constructor of the base class, and then copies the new member object of the derived class.
If you write a copy constructor of a derived class, you need to pass parameters to the corresponding copy constructor of the base class.

For example:

C::C(const C &c1): B(c1) {...}

Destructors are not inherited, and derived classes declare themselves
The declared method is the same as the destructor of a general class (when there is no inheritance relationship).
There is no need to explicitly call the destructor of the base class, and the system will automatically call it implicitly.
Destructors are called in the reverse order of constructors.

P68-P73

Identification and access of derived class members

When the derived class has the same member as the base class:
If not forcibly specified, the member with the same name in the derived class is used through the derived class object.

d.Show();   =    d.Derived::Show();

If you want to access a hidden member with the same name in the base class through a derived class object, you should use the base class name qualification.
d.Base::Show();

If you want to access a hidden member with the same name in the base class through a derived class object, you should use the base class name qualification.

d.Base::Show();

In multi inheritance, when a member with the same name appears between the base class and the derived class, or between the base classes, there will be ambiguity in access

Solution: virtual base class

Solution 1: use the class name to qualify c1.A::f() or c1.B::f()
Solution 2: hide the same name, declare a member function f() with the same name in C, and then call A::f() or B::f() as needed

virtual base class

Introduction of virtual base class
Used where there is a common base class
statement
Modify the base class with virtual, for example: class B1:virtual public B
effect
It is mainly used to solve the ambiguity problem caused by multiple inheritance of the same base class
Provide a unique base class member for the farthest derived class without multiple copies
be careful:
In the first level of inheritance, the common base class should be designed as a virtual base class.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-dyomqcri-1631360818283) (C: \ users \ Dell \ appdata \ roaming \ typora \ user images \ image-202012222210343155. PNG)]

In the farthest derived class C, there is only one copy from class B

C obj;
obj.b; //B is the protected member in B

The class specified when creating an object is called the farthest (farthest) derived class.

Members of a virtual base class are initialized by the constructor of the farthest derived class by calling the constructor of the virtual base class.

In the whole inheritance structure, all derived classes that directly or indirectly inherit the virtual base class must give the call to the constructor of the virtual base class in the member initialization table of the constructor. If not

If it is listed, it means that the default constructor of the virtual base class is called.

When creating an object, only the constructor of the farthest derived class calls the constructor of the virtual base class, and the calls of other base classes of the derived class to the constructor of the virtual base class are ignored.

Derived(int var) : Base0(var), Base1(var), Base2(var)

When creating an object, only the constructor of the farthest derived class calls the constructor of the virtual base class, and the calls of other base classes of the derived class to the constructor of the virtual base class are ignored

11 virtual function

When the virtual function is redefined, the function prototype must be completely consistent, including: the return type, function name, number of parameters, parameter type and order must be completely consistent with the original function

That is, the same prototype function modified with virtual in both the base class and the public derived class is a virtual function.

Distinguish between virtual functions and function overloads (formal parameters, different return values)

Virtual can only modify the functions of the base class, and the virtual keyword can be omitted before the homogeneous functions in the subclass. Such a family of functions is still virtual

That is, when a derived class redefines a virtual function, the member function will be a virtual function regardless of whether the virtual keyword is used or not

Destructors with virtual function classes must be virtual destructors

Declaration: virtual < type > function name (parameter table);

Out of class definition: you can not write the keyword virtual. The default value of formal parameters of virtual functions should be written in the base class.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8UDRMiPX-1631360818284)(C:\Users\DELL\Desktop \ capture. PNG)]

Call the subclass virtual function through the pointer and reference of the base class;
You cannot call a subclass virtual function through the base class object name

Once the reference is assigned, it cannot be changed

Calling a virtual function through a reference to a variable is defective:
Once a reference is initialized, it cannot be reassigned

General method

Through function calls, function parameters are references

If a virtual function is defined in a class, its destructor should also be described as a virtual function

If the destructor of the base class is a virtual function, the destructor of its derived class is also a virtual function

When constructing, first construct the base class, and then construct the derived class. The opposite is true in the case of deconstruction.

Pure virtual function

class Class name
{...
        virtual Return value type function name(Parameter table) = 0;
...
 };

After a pure virtual function is declared in a base class, the function body cannot be defined in the base class
The concrete implementation of pure virtual functions can only be completed in derived classes
Pure virtual functions exist to achieve polymorphism
Pure virtual functions are not implemented and are only defined as 0.

If there is at least one pure virtual function in a class, the class becomes an abstract class.

Abstract class objects cannot be declared.

Abstract classes that inherit only as base classes and have no derived classes are meaningless.

Functions in abstract class objects are declared in abstract classes, but can only be used in subclasses.

You can define pointers and references to abstract classes, which must point to or reference derived class objects.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-7qspvfbz-1631360818285) (C: \ users \ Dell \ appdata \ roaming \ typora user images \ image-20201218092503790. PNG)]

p1 points to a derived class. new cat does not need to be followed by a variable name. Pure virtual functions can only be called in subclasses.

12 operator overloading

"Operator overloading" is for the original operators in C + +. It is impossible to create new operators through overloading.
You can overload almost all known operators
Except for 5 operators:. *::?: sizeof
Other operators can be overloaded.
You cannot set default values for overloaded operator functions, and you cannot omit arguments when calling.
Except for the two special operators new and delete, any operator that is overloaded as a member function must not be overloaded as a static function.

=, [], (), - > and all type conversion operators can only be overloaded as member functions and cannot be overloaded for enumeration type operands.
Assuming that the binary operator + has been overloaded as a member function of a class, and c1 and c2 are objects of the class, c1.operator + (c2) has the same meaning as c1 + c2.
If + is overloaded as a non member function of this class, operator + (c1, c2) has the same meaning as c1 + c2.
Overloaded operators maintain their original number of operands, priority and associativity.
Semantics should be consistent with known functions
For example, you cannot overload "+" with "-"

Function type operator operator(Formal parameter table) // There is no space between operator and operator
{
    Function body;
}

Member function:

+, -, pre + +, post++

The object itself is an operand, and the number of parameters in the formal parameter table is 1 less than the number of operation items

operator + (c1, c2) and c1 + c2

clock operator+(const clock &c) const;

clock clock::operator+(const clock &c) const // Need to be as like as two peas.
{
    clock temp;
    temp.hour = hour+c.hour;
    temp.min = min+c.min;
    temp.second = second+c.second;
    temp.format();
    return temp;
}

clock operator-(const clock &c)
{
    int temp1 = hour*3600+min*60+second;
    int temp2 = c.hour*3600+c.min*60+c.second;
    int ans = temp1-temp2;
    clock temp(0,0,ans);
    return temp;
}

clock& operator++() 
// ++c1, the reason for passing reference is that the function returns a temporary variable. When + + (+ + c1) is used together, there will be an error when no reference is passed
{
    second++;
    format();
    return *this;
}

clock operator++(int)
// c1 + +, the post + + does not exist. The default is to pass the int parameter. The object old is destructed when the function returns, and there is no index when the function returns
{
    clock old(*this);
    second++;
    format();
    return old;
}

Assignment functions can only be member functions

The type conversion function can only be a member function, and the return value is not required during function definition.

fraction& fraction::operator=(fraction f)
{
    num = f.num;
    den = f.den;
    return *this;
}

fraction::operator long()
{
    return num/den;
}

Remove subscript

int& int_array::operator[](int index)
{
    if(index < 1 || index > size)
    {
        delete []data;
        exit(2);
    }
    return data[index-1];
}

String deep copy

//Operation =, str=str2
STRING& STRING::operator=(const STRING &s)
{
    if(&s==this)	
		return *this;
	if(p)
		delete[]p;
	if(s.p==NULL)
		p=NULL;
	else
	{	p=new char[strlen(s.p)+1];	//New to create a new object, and then copy
		strcpy_s(p, strlen(s.p) + 1,s.p);
	
	return *this;
}

The object old is destructed when the function returns and has no index when it returns

Friend function:

The number of parameters in the formal parameter table is the same as the number of operation items

<< >>

Input and output functions can only be friend functions

c does not change when output, so const references

friend ostream& operator<<(ostream &o, const clock &c);

ostream& operator<<(ostream &o, const clock &c) //You do not need to add friend when defining a function
    // In the function definition, function type class name:: function name
{
    return o << c.hour << ":" c.minute << ":" << c.second;
}

c will change when output, so add a reference directly

istream& operator>>(istream &i, clock &c)
{
    char ch;
    i >> c.hour >> ch >> c.min >> ch >> c.second;
    c.format() // Format directly after input
    return i;
}

+, - same

friend clock operator+(clock c1, clock c2);

clock operator+(clock c1, clock c2) // Friend functions do not belong to a class, so there is no need to add a definition field
{
    return clock(c1.hour+c2.hour,c1.min+c2.min,c1.second+c2.second); 
    // No variable name is required, which is equivalent to forced type conversion
}

Front

Change the first operand, passing a reference.

Returns a reference

friend clock& operator++(clock &c);

clock& operator++(clock &c)
{
    c.second++;
    c.format();
    return c;
}

Post

Change the first operand, passing a reference

Returns a temporary variable with a value of

friend clock operator++(clock &c, int i)
{
    clock old(c);
    c.second++;
    c.format();
    return old;
}

friend clock operator++(clock &c, int i)
{
    c.second++;
    c.format();
    return clock(c.hour,c.min,c.second-1);
}

14 template class

Parameterize the type of objects processed by the program, so that a program can be used to process many different types of objects

Function template

Function template format

template  <typename T>
 Type name function name(Parameter table)
 {Definition of function body}

template  <class T>
 Type name function name(Parameter table)
 {Definition of function body}

The template parameter table can contain basic data types or class types. Type parameters need to be prefixed with typename or class. If there is more than one type parameter, each type parameter must be prefixed< The parameters in the template parameter table > must be unique and appear at least once in < function definition body >.
The function template definition is not a real function, and the compilation system does not generate any execution code for it. This definition is only a description of the function, indicating that it can handle the data types described in the type form parameter table separately each time.

The function template is only a description and cannot be executed directly. It can only be executed after being instantiated as a template function.

The template function has a feature. Although the template parameter T can be instantiated into various types, the parameters using the template parameter T must maintain exactly the same type.

It overcomes the cumbersome of C + + function overloading "rewriting several functions with the same function name"

template <typename T>
T abs(T x)
{  
    return x < 0 ? -x : x;
}

int main()
{
    int i = -20;
    int j = abs(i);         
    double k = -4.5;
    double t = abs(k);
    return 0;
}
Specialization of function templates
template <> 
Return type function name<Specialized data types>(Parameter table) {}


template <>  //Specialization
const char* tmin<const char*>(const char *a,const char *b) 
{
	return (strcmp(a,b)<=0)?a:b;
}

Class template

template <Template parameter table>
 class Class name
 { Class member declaration };
     
// Class template format

 template <Template parameter table>
 Type name class name<T>::Function name(Parameter table)

     
// Member functions defined outside the class template
     
template <class T>    
class Node{ 
private:
   T item; 
public:
   T GetElem();  
};

template <class T>      
T Node<T>::GetElem() {  
   return item;    
}

15 STL

The core content of STL includes container, iterator and algorithm

STL containers are often divided into sequential containers, associated containers and container adapters

The sequential type containers provided by C + + include vector, list and deque.
Association containers mainly include sets, multiset s, maps, and multiplemap s
Operator < < (ostream & O, const Clock & C) / / friend is not required for function definition
//In the function definition, function type class name:: function name
{
return o << c.hour << ":" c.minute << ":" << c.second;
}



Output time c Will change, so add a reference directly

```c++
istream& operator>>(istream &i, clock &c)
{
    char ch;
    i >> c.hour >> ch >> c.min >> ch >> c.second;
    c.format() // Format directly after input
    return i;
}

+, - same

friend clock operator+(clock c1, clock c2);

clock operator+(clock c1, clock c2) // Friend functions do not belong to a class, so there is no need to add a definition field
{
    return clock(c1.hour+c2.hour,c1.min+c2.min,c1.second+c2.second); 
    // No variable name is required, which is equivalent to forced type conversion
}

Front

Change the first operand, passing a reference.

Returns a reference

friend clock& operator++(clock &c);

clock& operator++(clock &c)
{
    c.second++;
    c.format();
    return c;
}

Post

Change the first operand, passing a reference

Returns a temporary variable with a value of

friend clock operator++(clock &c, int i)
{
    clock old(c);
    c.second++;
    c.format();
    return old;
}

friend clock operator++(clock &c, int i)
{
    c.second++;
    c.format();
    return clock(c.hour,c.min,c.second-1);
}

14 template class

Parameterize the type of objects processed by the program, so that a program can be used to process many different types of objects

Function template

Function template format

template  <typename T>
 Type name function name(Parameter table)
 {Definition of function body}

template  <class T>
 Type name function name(Parameter table)
 {Definition of function body}

The template parameter table can contain basic data types or class types. Type parameters need to be prefixed with typename or class. If there is more than one type parameter, each type parameter must be prefixed< The parameters in the template parameter table > must be unique and appear at least once in < function definition body >.
The function template definition is not a real function, and the compilation system does not generate any execution code for it. This definition is only a description of the function, indicating that it can handle the data types described in the type form parameter table separately each time.

The function template is only a description and cannot be executed directly. It can only be executed after being instantiated as a template function.

The template function has a feature. Although the template parameter T can be instantiated into various types, the parameters using the template parameter T must maintain exactly the same type.

It overcomes the cumbersome of C + + function overloading "rewriting several functions with the same function name"

template <typename T>
T abs(T x)
{  
    return x < 0 ? -x : x;
}

int main()
{
    int i = -20;
    int j = abs(i);         
    double k = -4.5;
    double t = abs(k);
    return 0;
}
Specialization of function templates
template <> 
Return type function name<Specialized data types>(Parameter table) {}


template <>  //Specialization
const char* tmin<const char*>(const char *a,const char *b) 
{
	return (strcmp(a,b)<=0)?a:b;
}

Class template

template <Template parameter table>
 class Class name
 { Class member declaration };
     
// Class template format

 template <Template parameter table>
 Type name class name<T>::Function name(Parameter table)

     
// Member functions defined outside the class template
     
template <class T>    
class Node{ 
private:
   T item; 
public:
   T GetElem();  
};

template <class T>      
T Node<T>::GetElem() {  
   return item;    
}

15 STL

The core content of STL includes container, iterator and algorithm

STL containers are often divided into sequential containers, associated containers and container adapters

The sequential type containers provided by C + + include vector, list and deque.
Association containers mainly include sets, multiset s, maps, and multiplemap s
Container adapters mainly refer to stack s and queue s

Posted by nemesis1931 on Sat, 11 Sep 2021 19:03:32 -0700