Why learn C++ :

Aside from the professional use of C++ in some industries such as the Internet of things, high performance engines (games, etc.) and various operating systems, whether as Java development or other development, our knowledge system must have operating system related knowledge, and if we want to further understand the operating system, Understanding some of its code is, of course, essential. Or, the development of some high-performance tools or components, these, are inseparable from C and C++, and the learning of C++ in fact, basically have learned some things C (if you have not been exposed to C), based on the 80-20 rule, is basically enough.

The origin of C++ language:

In 1982, Dr. Bjarne Stroustrup from BELL LABS of AT&T introduced and expanded the concept of object-oriented on the basis of C language, thus creating C++, a programming language, which is also called C with class. Dr. Bjarne Stroustrup is also known as the father of C++.

Recommended c++ learning development tools

Windows use VC, MAC use Xcode can be strongly recommended to use Qt Creator to learn development, you can also learn the Qt library

C + + syntax

Recognize C++ objects:

C++ functions and objects:

  • Annotation (basically similar to Java annotations)
/ *... * / / /...Copy the code
  • Input output stream

Cin and cout are C++ functions that perform input and output operations, defined in the istream header. Example:

cout << "" << endl; //c stands for c language, out stands for output, endl stands for newlineCopy the code
  • Using namespaces namespaces are a mechanism in the C++ language for wrapping library names

    Objects and functions in the C++ standard class library belong to the STD namespace. When using these functions and objects, use namespace STD
    #include "iostream" #include "cmath" using namespace STDCopy the code
    • Note when using the STD namespace: when using a HEADER file in C, write it as “xxx.h”; when using a header file in C ++, do not add “.h “.
Namespaces can be customized, can be nested, such as wang defined A namespace, Li defined B namespace, even if they have the same name, the same function can be called by the namespace :: function name.Copy the code
  • Object definition and initialization
C: int x; x=0; Int x=0; Int x(0); int x(0); This type of initialization syntax is called constructor syntax in c++Copy the code
  • Function prototype and its return value
A function should be typed, and a return statement should be used to get the result. (this is similar to Java, but many Java applications refer to c++.) Example: ' ' 'int result(int a,int b){int d; d = a+b; return d; } example: int result(int a,int b); Void main(){// the main function... z = result(x ,y); // Call the defined function... } int result(int a,int b){// define function int d; d = a+b; return d; } ` ` `Copy the code
  • Const modifier and preprocessor

#define PI 3.1415 #define PI 3.1415 #define PI 3.1415 #define PI 3.1415 #define PI 3.1415 Const int PI = 3.1415; Const int PI(3.1415); When you define a constant using const, you must give it a value unless it is extern (an external, or global, variable). Starts with #, breaks down into macro definitions, file inclusion, and conditional compilation.

  • The rules for writing a program

Notice the indent alignment, case sensitive, similar to Java, but different.

C++ language features of procedural programming

  • Function overloading
(similar to Java) C++ allows multiple versions of a function to be defined, allowing a function to do more than one thing, i.e., the same function name to be defined multiple times. Int Max (float a,float b){return a > b? a:b; } int max(int a,int b,int c){ int d; d = a > b ? a:b; return d > c ? d:c; } int max(int a,int b){ return a>b ? a:b; As shown in the example, overloaded functions are characterized by the same function name, different number of arguments, or different parameter types.Copy the code
  • Void indicates an empty type, or no type, indicating that a function returns no value.

    2. The Boolean type (logical, Boolean) is 1 byte, representing the true and false in the logical operator.

    Int and short must be at least 16 bits long must be at least 32 bits short must not be longer than int. Int must not be longer than long

    4. The value of the char type is 1 byte.

    We can use sizeof to see the length of these data types:

    cout << sizeof(bool) << endl; cout << sizeof(int) << endl; cout << sizeof(short) << endl; cout << sizeof(long) << endl; cout << sizeof(char) << endl; cout << sizeof(float) << endl; .Copy the code

    6.& Take address (take the address of a variable) example:

    int x; int *p; //p is a pointer variable. A pointer variable can store the address of the variable. / / & said take out the address of the variable x, x p = & remove the address of the variable x x said after deposited in the pointer variable pCopy the code

    7. Constants are integers: the 0 prefix indicates a hexadecimal number; the 0x prefix indicates a hexadecimal number; the L and I suffixes indicate a long integer constant; the real type: F and F suffixes indicate a float constant. Real numbers with L, I suffixes denote long double; Double without prefix or suffix.

  • Dynamically allocating memory

Pointer variable = new type \[size]; The new operator obtains the first address of the newly allocated space, assigns the value to the pointer variable, and uses the space according to the addition or subtraction of the pointer variable. (unlike Java, Java has a garbage collection mechanism to automatically free memory, while c++ does not.) delete to free memory. delete p;Copy the code
  • How to use the reference
A reference uses the alias of a variable. Definition form: data type & alias = object name; Function: The alias name and the object name correspond to the same object and share the same memory. Changes to the alias cause changes to the original object. Example: ' ' 'int x; int & a = x; //a is an alias for the variable x. A and x are completely equivalent. A reference that cannot define a reference, as shown in the error example: ~~int && r=x; Use a typedef to define an alias of a type. Example: ' 'typedef long int lint; //long int i; lint i; // Lint I is equivalent to long int ICopy the code
  • Use the const qualifier for Pointers
1. Lvalue and Rvalue expressions: E1 = E2; E1 is an lvalue and can be modified; int *p,x = 1; *p = 2; &p represents the address of the pointer p. 2. Pointers to constants and const Pointers const definition: indicates that an expression that is const cannot be changed. Example: ' ' 'int x = 11; const int *p; // Const int *p = &x; Int * const p = &x; int * const p = &x; // Write correctly (note: p is not changeable, but *p is) 3. Examples of constant Pointers to constants: ' ' 'int x = 11; const int * const p = &x; // p is immutable, *p is immutableCopy the code
  • Generic algorithms are applied to ordinary arrays
Generic algorithms are a set of operations provided by the C++ Standard Template Library. These operations can simplify array operations. To use these operations you must include the header file \<algorithm> assuming that a and b are two array names with length len example: ' 'reverse(a,a+len); Copy (a,a+len,b); // Copy (a,a+len,b); Reverse_copy (a,a+len,b); reverse_copy(a,a+len,b); // Copy the contents of array a to array b sort(a,a+len); // Sort (a,a+len,greater<type>()); Int find(a,a+len,value); int find(a,a+len,value); Copy (a,a+len,Ostream_iterator<type>(cout," delimiter string ")); //Ostream_iterator is the output stream operator, <type> is the type of the array to be output, cout is the output stream operation, and "delimiter string" is the delimiter characterCopy the code
  • Program editing, translation, run the program from scratch to edit, out of the C++ source code comparison C and C++ files of various suffixes (due to historical reasons, it can be described as a lot of patterns, now only show the unity of) :

    language The header file The source file
    c .h .c
    c++ .h, but openCV uses.hpp Windows platform.cpp, Linux platform.cc
    Source code is compiled for translation
    There are a number of c++ compilers, including MSVC, GCC, Cygwin, and MingW (pronounced Cygwin and MingW), as well as a few smaller and newer versions. ICC (Intel C/C++ Compiler), BCC (Borland C/C++ Compiler, dying out), RVCT (ARM assembler /C/C++ Compiler, built into ARM IDE — RVDS), Pgi Compiler…

    The most common ones we use under Linux: GCC, formerly known as the GNU C Compiler, gradually supported more languages (C++, Fortran, Pascal, Objective-C, Java, Ada, Go, etc.) and became the GNU Compiler Collection (GNU Compiler Suite). GNU is a set of compilers developed by the GNU Project to support multiple programming languages. GCC is a well-known example of the evolution of free software. It is distributed by the Free Software Foundation under the GPL protocol and is the standard compiler for most Unix like Linux, BSD, Mac OS X, etc., and is also applicable to Windows (implemented through other porting projects, MingW, Cygwin, etc.). GCC supports a variety of computer system chips, such as x86, ARM, and has been ported to a variety of other hardware platforms. Sometimes, downloading a third-party tool in linxu will prompt us to download the relevant GCC dependencies, because the tool needs to be compiled using GCC due to c++ development.

Execution is the compilation and linking of c++ compiled files

Evolution from structure to class:

Structural evolution:

  • The structure has undergone qualitative evolution
C++ allows functions defined in a structure to become member functions. Define both member variables and member functions in the structure. Use format: structure object. Member variables structure objects. Examples of member functions: ' ' '#include <iostream> // Introduce header IO using namespace STD; Struct point{//point is the name of a c++ data structure, similar to double x,y; void updatexy(double a, double b){ x = a; y = b; } void display(){ cout << x << "\t" << y << endl; //endl = newline; Void main(){point p; // indicates that p is defined, which, unlike Java, already contains the = new.. After the action, so can directly call p.updatexy(1.5,1.7); p.display(); cout << p.x << "\t" << p.y << endl; } ` ` `Copy the code

2. Encapsulation If the private keyword is used when defining a structure, encapsulation is generated. Example:

Struct point{private: // struct point{private: double x,y; // In this case, in main, you can use the point variable name directly. Public: // In Java, you can only write a public.... void updatexy(double a,double b){ x = a; y = b; } void display(){ cout << a << "\t" << b << endl; }};Copy the code

When defining a structure, using private generates encapsulation, indicating that members are private and can only be used within the structure through public member functions. If private is not added, the default value is public. Note that the class is defined as private by default.

  • An object that uses a constructor to initialize the structure

When defining a structure, the function with the same name as the structure is called the constructor. Function overload occurs when a defined function has the same name as a defined function but has different parameter types or numbers. Example:

struct point{ private: double x,y; public: point(){}; point(doube a,double b){ x = a; y = b; } void updatexy(....) {... }... }Copy the code

Similar to Java classes, constructors are automatically executed when the struct object is defined, and the invoked constructor is automatically selected based on whether it is initialized or not. The distinction here is: If the object is not a new object, the variable name of the object will be null. If the object is a new object, it will not only create an object, but also automatically initialize the object, which means that the Java object creation process includes initialization. In c++, the object is defined, but the initialization process is controlled by us. We can call the constructor with parameters, and the initialization process is completed after the object is defined.

The structure evolves into a simple class:

Replacing a struct with a class becomes the standard definition of a class. Example:

class point{ private: double x,y; public: point(){}; point(double a,double b){ x = a; y = b; }; void updatexy(double a,double b){ x = a; y = b; } void display(){ cout << a << "\t" << b << endl; }};Copy the code

Representation of class diagrams (UML, unified Modeling Language, etc.) :

point
-x : double

-y : double
+point()

+updatexy()
Where, point is the class name, x and y are class attributes (member variables), point, updatexy and display are class operations (member functions).

Procedural and object-oriented:

Intuitively from a problem to distinguish: give two coordinates, calculate the distance between highlights, and output. 1. Procedure oriented solution step: Step: + Input x1,y1,x2,y2 four data to calculate the distance (x1,y1) and (x2,y2) output the calculated distance 2. Point A(x1,y1) point B(x2,y2) define the object, then get the coordinates to calculate the distance and output

C++ object-oriented programming features

  • object

Three elements: object name, property, and operation

Use classes and objects

  • Using classes and Objects 1. Using Strings
string
– str
+string()

+find()
This class is an internal predefined class in the c++ language. To use this class in a program, you must add the header #include <string>;

#include <… #include <… > and # include “…” .

Class initialization: string str1 = “A”; string str1(“hello “); string str2 = “world”; The complex class is used to define a complex number of objects. Use the #include

header to define the format: complex

num1(1,2); When you use classes from the standard class library, you must add header files. Objects are defined in a similar way to variables. An object can be initialized when it is defined. Objects of the same class are distinguished by object properties. Objects of different classes have different member functions that perform different operations. A class is an abstraction of objects that have the same characteristics and operations.

Functions and function templates

The parameters of a function and how they are passed

There is only one parameter passing mode in C language: value passing (value passing is divided into variable value passing and variable address value passing). C++ is divided into: value passing and address passing (reference passing), similar to Java. Parameters are passed in different ways: object as parameter, object pointer as parameter, object reference as parameter. The declarative form of a reference: data type & alias = object name; int x = 21; int &a = x; The reference object is not an antithesis, it shares the same address space as the original object and does not occupy memory. When a pointer to an object is used as an argument, the address of the argument object in the pointer variable.

The return value of the

Similar to Java, but with more pointer types.

Inline function

When defining a function, the inline keyword indicates that the function is inline. Example:

inline int wheatherNumber(char c){
 return c > '0' && c < '9' ? 1:0;
}
Copy the code

Inline function in the program when the program is compiled, the function is replaced to the function call position in the program, resulting in the program becomes longer and efficiency is improved. Note: Inline functions cannot contain loops or switch statements. Inline functions are short and should be declared or defined before calling

A function template

Some functions are overloaded with the same number of parameters, but different types. In this case, overloaded functions are more tedious, which can be realized using function templates. Example:

template <class type> type max(type a , type b){ return a > b ? a:b; } void main(){ int x = 1,y = 2; Double x1 = 1.2,y = 2.1; int z; double z1; z = max(x,y); z1 = max(x1,y1); Cout << "Max: int type" << z << "dobule type" << z1 <<endl; }Copy the code

After a function template is defined, the function call determines which version of the function is called based on the type of the function arguments. A function that determines the types of parameters when the function executes is called a template function.

Classes and objects

Class and its instantiation

  • The definition of a class
{private: // private data members and member functions public: // public data members and member functions protected: // protected data members and member functions}; Void class name :: function name (){}Copy the code

:: is called a domain qualifier and indicates that the function is a member function of the class. Use the field qualifier to define functions outside the class. If you want to define them inline, use the inline keyword. Functions defined within a class default to inline functions.

  • The use of objects of a class is similar to the use of variables. Declare/define an object, use it directly by its name, use it through a reference to it, and use it through a pointer to it.
  • Data encapsulation is similar to structure encapsulation

The constructor

  • If there is no constructor defined in the class definition, the c++ compiler automatically generates a default constructor with no arguments, similar to: point(){}, that does not initialize the object. If a constructor is defined in a class, the default constructor is no longer generated.
  • Constructors have no return value, which can reduce the work of the compiler and improve efficiency. The constructor has the same name as the class. Constructors can be overloaded. The constructor is automatically called by the system.
  • Constructor and operator new
New works together with the constructor, that is, new first allocates memory to an object and then automatically calls the constructor to initialize that memory. Example: ' 'void main(){Point * PTR = new Point; Point *ptr1 = new Point(1,2); delete ptr; delete ptr1; } ` ` `Copy the code

The dynamic object created by new can only be deleted by delete, and will free up space.

  • Copy constructor
< class name >::< copy-initialize constructor >(const class name & reference name)Copy the code

The destructor

The destructor is called automatically by the compiler. The name of the destructor is preceded by the class name with ~. The destructor has no return value and can be displayed as void.

  • Define the destructor
Class Point{private: int x,y; public : Point(const Point&); Point(int a = 10,int b = 10); ~Point(); }... The constructor is called once and the destructor is called once for each element of the object group of class. The destructor for the global object array is called before the program ends.Copy the code
  • Destructor and operator DELETE The destructor is automatically called after delete. As opposed to new.
  • The default destructor compiler automatically generates an empty destructor for classes that have no destructor, similar to the constructor. The constructor is called several times to allocate memory, the memory is freed several times, and the destructor is called several times.

This pointer

The this pointer is a c++ implementation powder-like mechanism that connects an object to the member functions it calls. The this pointer ensures that each object can have its own data members. (Similar to Java)

Point::Point(int a=0,int b=0){
 this->x=a;
 this->y=b;
}
point::Point(const Point &p){
  this->x=p.x;
  this->y=p.y;
}
Copy the code

Properties of classes and objects

  • Properties of objects
1. Objects of the same class can assign values to each other; 2. You can use an array of objects; 3. You can use Pointers to objects. 4. Objects can be used as function arguments; 5. When an object is used as a function parameter, you can use the object, object reference, and object pointer. An object can be used as a member of another class.Copy the code
  • The nature of the class
2. Incomplete class declaration Memory is allocated only when objects generated by the class are used. References to a class before it is fully defined. Incomplete declarations are used only for classes and structures 3. Empty classes 4. Default control permissions in class scope classes are privateCopy the code

A file specification for object-oriented programming

  • Compile the instruction
  • Use conditional compilation in header files

#if …

Special functions and members

Static members

1. Static member variables can only be initialized outside the class. 2. Static member variables can be accessed by any member function in a class. 3. Access to static members is normally qualified by the class name. 4. Static member variables are members of a class, not members of an object. 5. The static member already exists before the object is created. 6. Static members have no this pointer and cannot be accessed except by reference. (Similar to Java, but more powerful than Java.) Static members include static objects.

A friend function

You can achieve unrestricted access between two classes to members of another class. Friend functions can access private members, public members, and protected members. A friend function can be a class or function. Friends need to use the members of the class through the object. There are three forms of friends: 1. Ordinary functions as friends of a class example:

class Point{ double x,y; public: Point(double x1,double y1){x = x1, y =y1} friend double max(Point & p1,Point & p2); }; Double Max (Point &p1,Point &p2){return p1.x+p1.y > p2.x+p2.y? p1.x+p1.y : p2.x+p2.y; }Copy the code

Examples of member functions of class A as friends of class B:

class A{ private: int x; public: A(int a){x = a; } int getX(){return x; } void fun(B & t); }; class B{ private: int y; public: B(int b){y = b; } int getY(){return y; } friend void A::fun(B & t); }; void A::fun(B & t){ t.y = x; }Copy the code

3. Class A is the friend of Class B

class B{ private: int y; public: B(int b){y = b; } int getY(){return y; } friend class A; }Copy the code

Const object

Const limits variables, Pointers, object functions, data members, and member functions. It cannot be changed. A const object can only call const member functions

class circle{ private: double r; const double PI; static int count; Public: circle(double a):PI(3.14159265354){// const member function r = a; count = count+1; }}Copy the code

The main function

The main function is an entry function, similar to Java, except that there can only be one main

Inheritance and derivation

Basic concepts of inheritance and derivation

Inheritance is the generic relationship between classes. (Conceptually, it is similar to Java, but Java only supports single inheritance.) Inheritance of a class means that a derived class inherits all data members and member functions of the base class. Used to indicate a generic relationship between classes, not a constituent relationship. The characteristics of derived classes are as follows: 1. Add new members. 2. Redefine an existing member function. 3. Change the access rights of the members of the base class.

Single inheritance

  • General form
    Class Derived class name: Access control base class name {private: member list; Public: list of members; Protected: member list; }Copy the code
  • Constructors and destructors of derived Classes When a member of a base class inherited from a derived class is initialized, the constructor of the derived class calls the constructor of the base class. Common forms of constructors for derived classes: Derived class name :: Derived class name (arguments): Base class name (arguments) {// function body} Constructors and destructors cannot be inherited.
  • A derived class uses the private members of the base class to preserve encapsulation. You can change the private qualification to protected (similar to Java)
  • Access permissions
  • Assignment compatibility rules
  • The isa relationship: inheritance and derivation. Has-a relationship: A class uses objects of another class as members. Public inheritance relationships are generally equivalent to ISA relationships.
  • Public inheritance access permission table
The base class Derived classes A base class object Derived object
private inaccessible inaccessible inaccessible
public public Can be accessed Can be accessed
protected protected inaccessible inaccessible
  • Private derived
When defining a derivation, use private qualification. The public and protected members of the base class become private.Copy the code
  • Protect the derived
When defining a derivation, use a proetcted qualification. In demoted use, the base class private becomes inaccessible, protect becomes private, and public becomes protected.Copy the code

Multiple inheritance

{private: // private member protected: // private member protected: // public member}

Ambiguity and its governing principles

  • When a derived class inherits functions of the same name from multiple base classes, use of those functions in the derived class must be qualified by the class name. Objects of derived classes that use these functions also need to be qualified by the class name!

  • Derived class dominate the base class of the same function In the base class and the members of the derived class has a name repetition, give priority to members of the derived class, if you want to access base class members, must add about domain symbol: : private members of the derived class cannot access, only the classes and friends can visit If a derived class to access base class members, members of the base class should use the protected.

Class templates and vectors

A class template

  • Class template basics
    Template <class T> class class name {..... }Copy the code
Class template object: class name < Template parameters > Object name (parameters); Template <class T> Return type class name <T>:: function name (argument) {// function body}Copy the code
  • A template class inherits from a normal class. A template class acts as a derivative of a normal class. The use of an inherited member is the same as that of an inherited member of a normal class. The template class derives from the template class. When a template class is used, the template class parameters must be specified.

Vector and generic algorithms

  • Defining a vector list a vector is a class version of a one-dimensional array in c++, used to hold multiple data of the same type. You can dynamically specify the number of elements in a vector. Generic algorithms can be used. (analogous to collections in Java) Vector declarations: vector < type > Vector name; Vector < type > Vector name (length); Vector < type > Vector name (length, a); Vector < type > Vector name 1(vector name 2); Vector < type > Vector name (a,a+ length); So a is the array name.

  • Vectors can not only access ordinary data types such as int and double, but also store objects, Pointers, and Pointers to objects.

  • The basic manipulation of vectors is analogous to arrays, as well as the use of generic algorithms.

Polymorphism and virtual functions

polymorphism

  • The assignment compatibility rule means that wherever du needs base objects, we can use objects of zhi’s public derived class instead. Through public DAO inheritance, derived classes get all members of the base class except for the constructor and destructor, and all members have the same access control attributes as the base class. In this way, the public derived class actually has all the functionality of the base class, and any problem that the base class can solve, the public derived class can solve. Substitution in the assignment compatibility rule includes the following:

1. Objects of derived classes can be assigned to objects of base classes.

2. Objects of derived classes can initialize references to base classes.

3. The address of a derived object can be assigned to a pointer to the base class.

  • Assignment compatibility and name domination in static linking. Class object and the function called one by one, the program can be compiled to determine the object call which function, known as static linking.

When a member function is called from a pointer: the called member function is a member function of the class to which the pointer belongs, that is, a member function that is determined by assignment compatibility rules

  • Dynamic link polymorphism
To enable the program runtime to determine whether the function called by the pointer is a base class or a derived class, namely: dynamic linking. Virtual functions can be used to achieve dynamic linking.Copy the code

Virtual functions

  • Virtual function format:
virtual double area(){ return 0; } Virtual functions cannot be static members.Copy the code
  • There are three prerequisites for using virtual functions to realize polymorphism: 1. The inheritance relationship between classes meets the assignment compatibility rules; 2. 2. Rewrite the virtual function of the same name; 3. Use Pointers (or references) according to assignment compatibility rules.

  • Constructors and destructors call virtual functions. Standard c++ does not support fictitious building functions. Virtual destructors are supported.

  • {virtual function type function name (parameter list) =0; } 2. A class that contains pure virtual functions is called an abstract class. A derived class that does not implement all the pure virtual functions in the abstract class is still abstract. Virtual void area()=0; void area()=0; 2. Virtual vodi area(){} // Empty

Multiple inheritance and virtual functions

First, multiple inheritance is a collection of multiple single inheritance.

Pointers and polymorphisms to class member functions

In a derived class, polymorphism occurs when a pointer to a member function of the base class points to a virtual function, and that virtual function is accessed through a base-class pointer (or reference) to an object.

Operator overloading and stream class libraries

Operator overloading

  • Overload the assignment operator for an object

  • Implementation of operator overloading

  • Examples of overloaded << >> and ++ operators:

    Ostream &operator<<(ostream& output, class name & object name){return output; }Copy the code
  • The difference between class operators and friend operators

  • Overloading of the subscript operator “[]”

Stream class library

  • The base class of the stream library calls the place where the output data is received the target and the place where the input data comes from the source