Chapter 2 begins learning C++

1. In c + +

/* First C++ program */ #include <iostream> using namespace STD; /* int main(void) {cout<<"Come up an C++"<<endl; cout<<"You won't regret it"<<endl; return 0; }

For a C++ program, there are mainly the following elements:

  • Notes: From the prefix//Or is it/ * * /logo
  • The preprocessor compiles the instruction#include
  • Function:int main()
  • Compiling instruction:using namespace
  • Function body: with{}enclosed
  • The use of c + +coutThe statement in which the tool displays the message
  • The end of themain()Function of thereturnstatements

1.1,main()The function header

Main () is called by the startup code that the compiler added to the program.

Function header description
main()And OS (UNIX/Linux, Windows, Mac OS, etc.) directly
interface.

Main () with empty parentheses takes no arguments.

int main(void)
{
    statement
    return 0;
}

The main() function describes the behavior of the function. The first line int main() function is called function heading, and the part enclosed in the curly braces ({and}) is called the body.

Function body: Computer instruction that indicates what a function should do.

In C++, each complete instruction is called a statement. All statements end with a semicolon.

The last statement in main() is called the return statement, and ends main().

⚠️ Note: C++ programs usually begin execution with the main() function. If not, the program is incomplete and the compiler will indicate that the main() function is not defined.

Both capitalization and case must be accurate

Special cases where the main() function is not required:

  1. In the WindowsDynamic Linking (DLL)The module.
  2. Single chip microcomputer or robot chip

1.2. C++ comments

Comments in C++ begin with a double slash (//). End with the end of the line.

What comments do: They provide explanations for your program and make it easy to understand.

Usually identifies a part of the program or an aspect of the code.

Note: The compiler does not run and ignores comments.

C++ also recognizes C language comments

C-style comments

  • Multiline commentSymbol:/ *and* /Between, in order to* /To end the comment.
  • Single-line commentsTo:Double slash (//)To start,End of each lineTo close.

1.3 Preprocessor and header files

If a program wants to use the C++ input or output tool, it must use two lines of code:

#include <iostream>
using namespace std;

Use #include as a precompiled directive, which is called a preprocessor directive.

Preprocessor operation: Replace or add text to source code before it is compiled.

Such as:

#include <iostream>

Files such as iostream are called include files ———— are included in other files, so they are also called header files.

Header file naming convention

Header file type convention The sample instructions
C++ Old Style In order to.hAt the end iostream.h C++ programs can be used
C Old Style In order to.hAt the end math.h C, C++ programs can be used
C++ New Style No extension iostream C++ programs can use namespace STD;
The converted C Prefix it with c, no extension cmath C++ programs can use, can use non-C features, such as namespace STD;

1.4 Namespaces

If you are using iostream in your program, you need to use namespace compilation directives to make them available to your program.

using namespace std;

Also known as the using compile directive.

1.5. C++ output using cout

    cout<<"Come up an C++"<<endl;
    cout<<"You won't regret it"<<endl;

The part enclosed in double quotes is the message to be printed.

In C++, a series of characters enclosed in double quotes is called a string, due to the combination of several characters.

<< indicates the path of information flow, and cout is a predefined object.

Initial operator overloading

<< can be either the insert or left-shift operator.

The typical case of operator overloading is that by overloading, the same operator has different meanings. The specific meaning is determined by the context.

Common examples of operator overloading

  • &—-> represents both the address AND bitwise AND operator.
  • *—-> denotes both multiplication and dereferencing a pointer.

Control charactersendl

cout<<endl;

Endl is a special C++ symbol that restarts a line.

Inserting endl in the output stream causes the screen cursor to move to the beginning of the next line.

Endl is defined in the header file iostream and is located in the namespace STD.

A newline

C++ also provided an early way of representing line breaks in C; C language symbol \n.

\n is treated as a character called a newline character, which is the restarting line of endl in C++.

When displaying a string, including a newline character in the string instead of adding endl at the end reduces the amount of input.

Cout <<"\n"; cout<<"\n"; cout<<endl;

1.6 C++ source code style

The style of source code in C++ follows the following rules:

  • Each statement is a line.
  • Each function has oneOpening curly braceAnd aClosing curly brace, two curly braces on one line each.
  • Statements in the function are indented relative to curly braces.
  • Relating to a function nameThere is no white space around the parentheses.

2. C + + statements

Program code example:

#include<iostream> using namespace std; int main() { int carrots; // declare an integer variable and results = 25; / / to variable assignment cout < < "I have" < < < < carrots "carrots." < < endl; carrots = carrots - 1; Cout <<" Look! Look! Now, I have "<< and results <<". <<endl; return 0; }

2.1 Declaring statements and variables

In C++, variables must be declared the first time they are used. You can avoid spelling mistakes that are difficult to spot.

Declarations usually indicate the type of data to store and the name the program uses for the data stored in memory.

A declaration statement in a program is called a definition declaration statement, or definition for short. Definition causes the compiler to allocate memory for a variable.

⚠️ Note: A declaration is not necessarily a definition.

2.2 Assignment statement

An assignment statement assigns a value to a storage unit.

The symbol = is called the assignment operator. 👉 Tips: Contiguous use of assignment operators is allowed in C++.

Assignment goes from right to left.

3. Other C++ statements

3.1 cin and cout

Cin uses the >> operator to extract characters from the input stream.

You can convert a list of characters entered through a keyboard (that is, input) into a form that is acceptable to the variable receiving the information.

Cout’s object properties contain an insert operator <<, which inserts the information on the right into the output stream.

The << operator concatenates multiple output statements.

3.2 Introduction to the class

Classes are one of the core concepts of C++ object-oriented programming (OOP).

What is a class?

A class is a user-defined data type.

To define a class, you need to describe what information it can represent and what operations it can perform on the data.

A class definition describes a data format and its usage, while an object is an entity created according to a data format specification.

#### two classes cin class and cout class

  • cinClass:Cost object
  • Cout: Object of the ostream class. The definition of the ostream class describes the data an ostream represents and the operations performed on it.

    Two classes are not built into the compiler.


    Pay attention to the point:
    classRepresents a data type
    All properties (including operations performed using it).
    objectIt’s based on the description
    Created entity.

The way messages are sent in C++

  • Using class methods (function calls, etc.)
  • Redefine the operator

4. The function

Two C++ functions

  • Returns a value
  • There is no return value

4.1 A function with a return value

A function that returns a value will generate a value, and the value will be assigned to a variable or other expression.

  • Called function: The function that is called
  • Calling function: Contains the called function
  • Return value: The value sent back

The argument is the information sent to the function, and the return value is the value sent back from the function.

👉 Tips: For the C++ compiler, a function’s parameter type and return value type must be the same.

⚠️ Note: C++ programs should provide prototypes for each function used in the program.

The function prototype must end with
The semicolon (;)The end. If the semicolon is omitted, the compiler assumes it is
The function headerThe body of the function that defines the function is required.

Don’t confuse function prototypes with function definitions

A function prototype describes only the function interface.

A function definition contains the code for the function.

👉 Tips: Provide a prototype before you use a function for the first time. You usually put the prototype before the main() function definition.

4.2 Function Variations

  • The keyword void is used in the prototype to specify the return type, indicating that the function has no return value.

    void bucks(double);
  • The keyword void takes no arguments. If you omit void and leave the parentheses empty, C++ interprets it as an implicit declaration that takes no arguments.

    int rand(void);

4.3 User-defined functions

For library functions, a prototype must be provided before it can be used, usually before the main() definition.

  • The format of a function is: a function header + a body of curly braces.

    type functionname(arguementlist)
    {
        statements
    }

    C++ does not allow function definitions to be nested within another function; each function definition is independent.

  • The function header

    For example,main()Function head.

⚠️ Note: keywords are special words and should not be used for other purposes.

Return cannot be used as a variable name, and double cannot be used as a function name.

4.4 User-defined functions with return values

For functions that have a return value, use the return keyword to provide the return value and end the function.

Property of a function

  • There are function headers and function bodies
  • Take a parameter
  • Return a value
  • You need a prototype

4.5 Using the USING compiler directive in multi-function programs

Four ways to give your program access to the namespace STD

  • willusing namespace std;On theBefore the function is defined, so that all the file functions can be usedNamespace STDAll of the elements of.
  • willusing namespace std;On theBefore the specific function is definedTo make the function availableNamespace STDAll the elements of.
  • Use analogues in specific functionsusing std::cout; Compile commands, notusing namespace std;Enables the function to use specified elements, such as cout.
  • Completely out of useCompiler usingWhile in need of useNamespace STDThe element is, using a prefixstd::.