The first intimate contact with C + + for the 2nd part
After browsing the world map of C + + "three points of the world", we have a basic understanding of C + +, which is a foot stepping into the door of C + + world. So how do we get our other foot into the door of the C + + world? Is it time to start writing C + + programs? Still is......
As we hesitated, we saw a person in front of a group of C + + beginners surrounded by a bunch of head-marks. We quickly squeezed into a look, oh, originally a C + + program is doing self-introduction.
2.1 Confessions of a C + + program
"Hello everyone, welcome to the wonderful C + + world. I am welcome to the C + + world-one of the simplest and most common C + + programs, my name is "HelloWorld.exe". Although I am simple and ordinary, but almost the world's most famous C + + program. Every beginner who comes to the C + + world with C + + 's first intimate contact is done through me. Before you listen to me, you must think that the C + + program is very mysterious, for example, how to create a C + + program? What parts of a complete C + + program are formed? What is the legendary source file? How is a C + + program executed? In fact, our C + + program is not mysterious, like everyone else, we have their own father and mother, have their own features and limbs, but also have their own life process. What the? You think that's incredible? Don't worry, listen to my one by one ... "
2.1.1 Creating C + + programs with Visual Studio
The first thing you're most interested in in the C + + world is getting started with a C + + program yourself. Most C + + programs are created from a software called the Integrated development environment (Integrated development environment,ide), which can be said to be a factory that creates C + + programs. While there are many integrated development environments that can be used to create C + + programs, we prefer visual Studio, developed by Microsoft Corporation. As an integrated development environment that has evolved over more than 20 years, Visual Studio has a variety of features: a flagship version for large-scale team development, a Professional Edition for personal development, and a free express version. If we just want to use Visual Studio for C + + learning, we can use the Visual C + + Express version of it. It is not only functional, but also small. More importantly, it is free and we can download the installation from Microsoft's website for free. Visual Studio is the most common development environment on the Windows platform, and for other development tools and development tools on the Linux platform, please refer to section 2.3 below.
Now, under my guidance, let's create our first C + + program in one step, using Visual Studio. No. 0 Step, create a new project. From the Start menu, locate the already installed Visual Studio and click Start. When you first start Visual Studio, it asks us to choose the interface layout settings, where we select the layout settings that apply to Visual C + +, and then wait a moment to see the start page of the Visual Studio gorgeous. In Visual Studio, all of our development work is done in a project, so the first step we use to write programs in Visual Studio is to create a project for managing Program Files: Click New Project on the left side of the start page, and in the New Project dialog box that pops up, Select the Visual C + + node in the tree view on the left, then select the project template "Empty Project" in the project type list on the right, then enter the project name "HelloWorld" below the dialog box and choose where the project will be stored, and finally click the "OK" button to complete the creation of the new project.
Figure 2-1 New Project
1th step, add the source file. The creation of the new project just set up an empty framework and wait for us to add some material to it. In Solution Explorer on the left, locate the source files branch under the HelloWorld project, and then right-click the source Files branch and select Add New item in the pop-up menu, and then you can get the Add Item dialog box. In the Add New Item dialog box, select the Visual C + + branch in the tree view on the left, and then select C + + files in the file type list on the right, then modify the file name to "HelloWorld.cpp" below the dialog box, and then click the "OK" button, the visual Studio creates a new HelloWorld.cpp source file for us and adds it to the project.
Figure 2-2 Adding a source file
2nd step, edit the code. With the blank source file, it is equivalent to the painter's good board, the writer put the manuscript, waiting for us to start writing code. In the HelloWorld.cpp file that has been opened, we edit the following code (a special reminder of the value here is that the punctuation should be in English):
#include <iostream>usingnamespaceint main () { // on the screen output "Hello world!" String cout<<"Hello world! "<<Endl; return 0 ;}
Figure 2-3 Editing the code
The 3rd step is to compile the execution program. Once the code has been edited, we can compile and execute the program to say hello to the C + + world. This step can be done with the menu command "debug-start (Not debug)", but more often, we do this by Ctrl+f5 shortcut keys. When we press the shortcut key, Visual Studio compiles the source file in the project, and if there is no error in the source file, it will generate the corresponding HelloWorld.exe executable, which will then start executing the program, thus printing a "Hello world!" in the DOS window. "The string greets the C + + world.
Figure 2-4 Hello world!
Best practice: Wait a minute, I haven't seen the output yet!
When we execute a program in Visual Studio, if the program does not need to interact with the user during execution, the DOS window that is opened when it executes is closed as soon as it finishes executing. If the program has a result output, we can't even see the output of the program. A program is finished, even the output is too late to see how this can be done?
To solve this problem, we can add a "system" ("pause") before the main function of the program is returned. Statement. For example:
int Main () { // ... // Let the program pause before it ends System ("pause"); return 0 ;}
With this statement, the program pauses before execution completes, so that we have enough time to see the output of the program. Naturally, this statement can also be used to improve the interactivity of the program, where it is needed to pause during program execution.
Another way to view the output of the program is to start the DOS window and then manually execute our application in a DOS window. In this way, the DOS window does not close after the program executes, so we also have time to view the output of the program.
After four simple steps, we easily wrote our first C + + program and finished our first close contact with C + +. In addition to creating C + + programs with Visual Studio, we can even take a purely manual approach to creating C + + programs. However, the basic process is the same in any way. If you use Visual Studio, you will be more productive with the help of development tools. If you use the manual approach, you can flexibly customize the entire development process to meet some of our individual needs. For beginners, the manual approach is slightly more complicated. The best course of study should be to start with Visual Studio and wait until you have a certain foundation, and you need to have more granular control over the program's writing process, and then use manual mode instead. This will not be in the entry stage by the complex manual way trapped in the footsteps, and in the advanced after the development tools are limited.
2.1.2 C + + program = precompiled instruction + program code + Comment
A perfectly formed. Don't look at me. Small, only a few lines of code, the implementation of the function is very simple, but I also have C + + program "facial Features and limbs": precompiled instructions, program code and comments, 2-5. In most cases, these three basic components are placed in a text file with the extension "CPP", which is referred to as a C + + source file. The source document recorded my "Five Senses and limbs" and planned my life. The creator of the source file is my designer. By modifying the source file, I can change my face, my life track, let me complete various tasks, realize various functions.
Figure 2-5 C + + program = precompiled instruction + program code + Comment
Now, let's take a look at my source files and get to know my "facial features and limbs".
1. Pre-compilation instructions
In the source file, the content that begins with "#" is the precompiled instruction. The purpose of this is to tell the compiler to make some pre-processing of the source file, such as inserting files, replacing strings, before actually compiling them, to get the source files that are finally involved in compiling. For example, in my source file HelloWorld.cpp, the first line is a precompiled directive that inserts a file:
#include <iostream>
Where the "#include" directive is used to insert the specified file into the location of the directive as part of the entire source file. Because such a file is always inserted in the head of a source file, we usually refer to such a file as the header file. Here we insert the "iostream" header file because we need to use the cout and Endl defined in the program to complete the output (for input and output of C + +, refer to section 2.2 below). Note that the file name after the "#include" directive has two representations: if you enclose a file name with double quotation marks, the preprocessor will first search for the file in the current directory (that is, the directory where the source file resides), if it does not exist, The file will continue to be searched under the project's include directory (including the project's default header file directory, which is the "\vc\include" folder under the Visual Studio installation directory, and the project additional header file directory set in the project properties), and if you use angle brackets <> To surround a file name, the preprocessor will search for it directly in the project's inclusion directory. So, usually we use "" To insert header files in the current project directory (such as the header files we created ourselves), and use <> to insert the library header files in various projects including the directory (iostream, for example). It is worth reminding again that all punctuation marks used in the code (the angle brackets used here, including the double quotes, commas, semicolons, and so on in the code below) must be in English. Some of the Chinese and English symbols are very similar, it is easy to confuse the beginner and cause compilation errors, which is especially worth the attention of beginners.
2. Program code
The body of a program code consists of several C + + statements (usually a single line of code that ends with a semicolon), which can be said to constitute the basic unit of the program. In my source file, the first C + + statement is:
using namespace std;
This statement indicates that the namespace I am using is std. The so-called namespace is the various identifiers in the program (such as cout and Endl here, we use these symbols to access the various elements of the program, in fact, it can be said that the names of these elements, so these symbols are also called identifiers) in the scope of the More specifically, you can refer to the 7.3.2 section for a description of namespaces. In C + +, any identifier is defined in a namespace, and the same identifier can be defined simultaneously in more than one namespace. This is like Zhang Jia Cun a person called Chen Liangjio, and Li Jia Cun also has a person called Chen Liangjio, we call "Chen Liangjio" this person, in order to express clearly, we must precede the name with a prefix, called "Zhang Jia Cun Chen Liangjio" or "Li Jia Cun Chen Liangjio". The namespaces in C + + are equivalent to "Zhang Jia Cun", "Li Jia Cun". Here, we use in the code behind the cout, Endl are from the Std this village, so we use this statement to tell the compiler, if you encounter an identifier without prefix (for example, here cout), you can go to the Std village to look for, if you can find, that is it (results, Found the std::cout in the Std village). Most of the content of C + + is defined in the Std namespace, so many times we need to use this statement in our code to introduce the STD namespace. Of course, if you do not use this statement, we can also precede the identifier directly with the namespace prefix, explicitly indicate that this is from a namespace identifier (in code, using Std::cout instead of cout, Std::endl instead of Endl).
The Next statement is:
int Main ()
This statement, together with the contents of the curly braces behind it, forms the main () function, also known as the primary function. A function is the most basic organizational unit in a C + + program, which organizes several statements together to implement a function. If a statement is equivalent to a cell in the human body, then the function is equivalent to a certain number of cells composed of some functional organs. and the main function here is the most important "organ" in a program. A C + + program must have a main function and only one main function. When the C + + program starts executing, it will first enter the main function, and then execute the statement one after the other, until the execution of the statement exits the main function, and the execution of the program is declared complete. It can be said that the main function defines a C + + program for a lifetime.
Know more: Why does a C + + program have to have only one main function?
When we double-click to execute the program, the process of executing the program will first create the main thread, the main thread and then the calling convention to start the run-time library, by starting the runtime library called the Convention good main function, from this start to execute the user's code. The main function is the execution entry for the main thread, so a C + + program must have a main function.
At the same time, a thread cannot have multiple execution portals. and in C + +, global symbols (variables, functions) can only have one definition. The main function, as a global function, can only have one.
The next step is a statement in the main function:
cout<<"Hello world! "<<endl;
cout is an output stream object defined in the header file "iostream", which is a predefined object of the C + + standard library and is typically used to output text or numbers to the screen. The previous use of the "#include" precompiled directive contains the "iostream" header file in order to use this object in your code. The input/output stream is described in more detail in a later section, as long as you know that the statement will "Hello world!" This string of text output to the screen can be. It is worth reminding again that the double quotes here must also be in English.
My last statement is:
return 0;
It indicates that the program completed successfully and returned (return). Typically, we return a value of 0 indicating that the program executed successfully (if an error occurs during the execution of the program, you can also return a different numeric value that represents the error message.) The executor of the program can accept the return value to determine if the program executed successfully. Here, the statements in the main function are executed, and my life ends here.
3. Notes
Comments are written by the source code to help the reader of the code (the Code post-maintenance staff, including the writer himself) to better understand the code, and in the code to write about a line or a piece of code of some explanatory text. Although comments in the source code do not participate in the final compilation and do not affect the functionality of the program, it improves the readability of the code and facilitates later maintenance. Here, for example:
// on the screen output "Hello world!" String
is a comment that explains the effect of the next statement, which allows us to have a better understanding of the code.
In form, comments in C + + can be divided into single-line comments and block annotations. "//" is a single-line comment character, followed by "//" until all the contents of the newline are commented. Because there is only one line of content, it is often used to make short explanations of the code. For example, the above comment is a typical single-line comment.
Block annotations in C + + we use a pair of "/*" and "* *" to indicate that everything that appears between the symbols is a comment. Because it can contain multiple lines of content, you can use block annotations when we need to explain the code in detail. For example:
/* This is a comment * /
Functionally, annotations are generally divided into introductory and explanatory comments. The preamble comment is located at the beginning of the program source file, which is used to describe the program's file name, usage, writing time, maintenance history, etc. In the example above, we can add a preamble comment to the first line of the source file to explain the functionality of the source file:
HelloWorld.cpp: On the screen output "Hello world! The string
The introductory notes are widely used in large projects. Typically, each project has its own defined, introductory comment format, which is used to explain the necessary information to the reader of the code. Here is an excerpt from an actual project that explains the name of the source file, its role, the history of the file's modification, and so on, helping the reader to better understand the code. You can use this as a template for writing your own introductory notes.
/////////////////////////////////////////////////////////////////////////AppDataView.cpp:implementation File////Cappdataview//This view was designed to display the APP Data////version:2.1//Date:september 2001//Author:chen Liangqiao//Email: [Email protected]//Copyright (c) 2002. All rights Reserved.////History :/*27.09.2001 Chen Liangqiao Added OnCreate (), OnUpdate (): Added USAG E of mesh tracer layers Added bugfix for Graphics zoom error30.10.2001 Chen Liangqiao Changed Order of MPR View only in _torchtonav08.11.2001 Zeng Me Added EUPD Atereason, used for Updateallview (), Added voxel trafo Changed the control p Anel due to new Ctestctrl*////////////////////////////////////////////////////////////////////////
Unlike the preamble comment, which is located at the beginning of the source file, the explanatory comments are scattered over the various parts of the source code to explain to the code reader the meaning of the code, the necessary questions, and so on. For example, the comment in the above example:
// output "Hello world!" on the screen "String cout<<"Hello world! "<<endl;
This explanatory note is used to explain to the code reader that the function of its next code is the output string "Hello world! ”。
Best practices: What is a good comment
Although the program's annotations do not affect the implementation of the program's functionality, the compiler does not read our comments, but a good comment can increase the readability of the program code and make the program easier to maintain. No one is willing to maintain a code without comments, which is tantamount to reading the heavenly book. So what kind of annotations are good notes?
First, make sure that the comment is in place.
A comment is a "hint and description" of the code that exists to help the reader of the code better understand the code. When we think that the code should not be interpreted "at a glance", or if the code needs to be specifically explained, it should be added with comments, additional explanations and explanations to help readers understand the code. For example:
//determines whether a floating-point number is an approximate integerBOOLIs_int (Doubled) { //subtract its integer part (int) d with floating-point number D to get its fractional part Doubles = d-(int) D; //determine if the fractional part is within the error range if(S >0.000001) return false; Else return true;}
The comments here are properly explained by the more difficult to understand code (if there is no comment, it is difficult to understand "double s = d-(int) D; What the meaning of this line of code is, improves the readability of the code.
Second, it's best not to comment where you shouldn't comment.
Comments are just "hints and descriptions" of the code, and if the code itself is already well-words too literally, there is no need to annotate it with "superfluous". It is also important to note that annotations are just short descriptive text, not exhaustive documentation. Note that the program can not be distracting, too many comments will be confusing, but reduce the readability of the code. For example, the comments in the following code are not appropriate:
//determines whether a floating-point number is an approximate integer//The parameter is the floating-point number that represents the input D//The return value is a bool value that indicates whether it is approximateBOOLIs_int (Doubled) { //subtract its integer part from a floating-point number and get its fractional part//where D is the floating-point number, and (int) d represents the integer part of the floating-point number Doubles = d-(int) D; //determine if the fractional part is within the error range if(S >0.000001) return false;//the fractional part is greater than the error range, indicating that the floating-point number is not an approximate integer and returns false Else return true;//the fractional part is less than the error range, which means that the floating-point number is approximate integer and returns True}
The comments in this code are also explained in detail to some very straightforward code, which goes far beyond the content of the code, so that it does not add to the readability of the code, but rather drowns the code in a complex comment, which reduces the readability of the code. Such comments are "superfluous" superfluous.
Also, you should develop good code-commenting habits. Add the necessary comments when you write your code, modify the corresponding comments when you modify the code, delete useless comments, and ensure that the comments are consistent with your code.
The annotations should be accurate and understandable, and avoid ambiguity. Wrong comments are not only useless but harmful.
The location of the note should be adjacent to the code described, and can be placed above or to the right of the code and not placed below. For example:
// on the screen output "Hello world!" String // comment on the code below cout<<"Hello world! "<<Endl; int 1024x768 // number of loops, commenting on the left-hand code
If your code is long, especially if you have multiple nesting, you should comment at the end of some paragraphs to see where the nested structure starts and ends. For example, a multi-loop code and its comments are as follows:
for int 0 ; + +i) {forint0; + +J ) {// algorithmic processing ... // J Cycle End // I loop End
Program code is not just written to the compiler, it is written to the programmer himself or others to see. There is no comment in the code for the compiler, but for programmers reading the code, the appropriate annotations can greatly improve the readability of the code and make the code easier to maintain. Thus, annotations are an essential part of C + + program code, and whether or not the program code contains the appropriate annotations is also a standard for measuring whether a programmer is good or not.
Precompiled instructions, program code and annotations together constitute my "five senses and limbs", but at this time I was just a text file suffix cpp, and to get the final executable EXE file, still rely on my father mother: compiler and linker.
Hello, C + + (3) 2.1 Confessions of a C + + program