# 21天学会c++（英汉对照，个人翻译，水平有限，供参考）-------第2天

1813人阅读 评论(0)

2nd Day

• ## The Parts of a C++ Program一个c++程序的构成

C++ programs consist of objects, functions, variables, and other component parts. Most of this book is devoted to explaining these parts in depth, but to get a sense of how a program fits together you must see a complete working program. Today you learn

c++程序由对象、函数、变量和其他的组成部分构成。本书的大部分是深度解释这些部分，但是为了对一个程序如何组合在一起有一个了解，必须来看一个完整的程序。今天你将学到：

• The parts of a C++ program.

一个c++程序的组成

• How the parts work together.

这些部分是如何工作的

• What a function is and what it does.
• 函数是什么且它能做什么

### A Simple Program一个简单的程序

Even the simple program HELLO.CPP from Day 1, "Getting Started," had many interesting parts. This section will review this program in more detail. Listing 2.1 reproduces the original version of HELLO.CPP for your convenience.

甚至第一天"入门"里的简单程序hello.cpp都有很多有意思的部分。这一节来详细复习一下这个程序。表2.1是为了你的方便，而复制的hello.cpp的原始版本。

Listing 2.1. HELLO.CPP demonstrates the parts of a C++ program.

表2.1hello.cpp演示一个c++程序的构成。

1: #include <iostream.h>
2:
3:  int main()
4: {
5:    cout << "Hello World!/n";
6:      return 0;
7: }
Hello World!


On line 1, the file iostream.h is included in the file. The first character is the # symbol, which is a signal to the preprocessor. Each time you start your compiler, the preprocessor is run. The preprocessor reads through your source code, looking for lines that begin with the pound symbol (#), and acts on those lines before the compiler runs.

在第一行，是使文件iostream.h被包含在此文件中。第一个字符是#，他是发给预处理器的一个信号。每当你运行编译器时，预处理器就会运行。预处理器读一遍源代码，寻找以#开始的行，在编译器运行前处理这些行。

include is a preprocessor instruction that says, "What follows is a filename. Find that file and read it in right here." The angle brackets around the filename tell the preprocessor to look in all the usual places for this file. If your compiler is set up correctly, the angle brackets will cause the preprocessor to look for the file iostream.h in the directory that holds all the H files for your compiler. The file iostream.h (Input-Output-Stream) is used by cout, which assists with writing to the screen. The effect of line 1 is to include the file iostream.h into this program as if you had typed it in yourself.

include是一个预处理指令，那就是说“紧跟一个文件名。寻找此文件并把它读到这里。”文件名两边的尖括号将使预处理器在你的编译器的头文件目录中搜寻文件iostream.h。头文件iostream.h(输入/输出流）由cout使用，cout支持使字符流写入终端屏幕。行1的作用就是把头文件包含进这个程序就像你自己亲手打得一样 。

New Term: The preprocessor runs before your compiler each time the compiler is invoked. The preprocessor translates any line that begins with a pound symbol (#) into a special command, getting your code file ready for the compiler.

新术语 ：每次调用编译器时，预处理器都会在编译器之前运行。预处理器把任何以#开头的行翻译成一个特定的命令，为编译器做好准备。

Line 3 begins the actual program with a function named main(). Every C++ program has a main() function. In general, a function is a block of code that performs one or more actions. Usually functions are invoked or called by other functions, but main() is special. When your program starts, main() is called automatically.

第3行是实际程序的开始，以一个名为main()的函数开始。每一个C++程序有一个main()函数。概括之，一个函数就是执行一个或多个操作的代码段。通常函数有其他的函数调用，但是main()函数特殊。当程序运行时，main()函数自动被调用。

main(), like all functions, must state what kind of value it will return. The return value type for main() in HELLO.CPP is void, which means that this function will not return any value at all. Returning values from functions is discussed in detail on Day 4, "Expressions and Statements."

main()函数和所有其他的函数一样，必须给出返回值的类型。在hello.cpp中，主函数的返回值类型是void，意思是这个函数不返回任何的值。函数返回值将在第4天"表达式和语句"中详细讨论。

All functions begin with an opening brace ({) and end with a closing brace (}). The braces for the main() function are on lines 4 and 7. Everything between the opening and closing braces is considered a part of the function.

所有的函数都以一个开大括号{开始，而以一个闭大括号结束。主函数的括号在第4行和第7行。括号间的一切都被认为是此函数的组成部分。

The meat and potatoes of this program is on line 5. The object cout is used to print a message to the screen. We'll cover objects in general on Day 6, "Basic Classes," and cout and its related object cin in detail on Day 17, "The Preprocessor." These two objects, cout and cin, are used in C++ to print strings and values to the screen. A string is just a set of characters.

这个程序的核心在第5行。类cout被用来往屏幕中打印一条信息。我们将在第6天"基础类"中讨论类，在第17 天"预处理器"中详细介绍cout和它的相关类cin。cout和cin这两个类在c++中用来往屏幕上打印一个串和数值。串是一些字符的集合。

Here's how cout is used: type the word cout, followed by the output redirection operator (<<). Whatever follows the output redirection operator is written to the screen. If you want a string of characters written, be sure to enclose them in double quotes ("), as shown on line 5.

这里说一下cout怎么使用：先是一个cout,后面紧跟输出重定位符号<<.紧跟此符号后面的任何数据都将被写到屏幕上。如果你想要输出一串字符，确保把他们包含在双引号中间，如第5行所示。

New Term: A text string is a series of printable characters.

新术语：文本串是一串可打印字符。

The final two characters, /n, tell cout to put a new line after the words Hello World! This special code is explained in detail when cout is discussed on Day 17.

最后的两个字符/n是告诉cout在hello world!后换新行。这个特殊符将在第17章讨论cout时详细解释。

All ANSI-compliant programs declare main() to return an int. This value is "returned" to the operating system when your program completes. Some programmers signal an error by returning the value 1. In this book, main() will always return 0.

所有ansi兼容程序声明main()函数时都返回一个int值，这个值当你的程序完成时将返回给操作系统。一些程序员通过返回值1来表明一个错误产生。本教材，main()总是返回值0。

The main() function ends on line 7 with the closing brace.

主函数在第7行以闭括号}结束。

• ### A Brief Look at cout简要的来看一下cout

On Day 16, "Streams," you will see how to use cout to print data to the screen. For now, you can use cout without fully understanding how it works. To print a value to the screen, write the word cout, followed by the insertion operator (<<), which you create by typing the less-than character (<) twice. Even though this is two characters, C++ treats it as one.

在第16天"流"中，你将明白如何使用cout在屏幕上打印一个数据。现在，你可以使用cout无需理解它是如何工作的。要想在屏幕上打印一个值，现写上cout,紧接着是插入操作符<<,也就是输两次小于符号<.尽管这是两个字符，但是c++把它作为一个来对待。

• Follow the insertion character with your data. Listing 2.2 illustrates how this is used. Type in the example exactly as written, except substitute your own name where you see Jesse Liberty (unless your name is Jesse Liberty, in which case leave it just the way it is; it's perfect-- but I'm still not splitting royalties!).
紧接插入符的是你的数据。表2.2说明了如何来使用。正确打出这个例子，除了把Jesse Liberty 替换成你自己的名字（除非你的名字就是Jesse Liberty ，这样你无需要替换；这样很好-----可是我可不想分担版税）。

• Listing 2.2.Using cout. 表2.2.使用cout.

1:     // Listing 2.2 using cout
2:
3:     #include <iostream.h>
4:     int main()
5:     {
6:        cout << "Hello there./n";
7:        cout << "Here is 5: " << 5 << "/n";
8:        cout << "The manipulator endl writes a new line to the screen." <<endl;
9:        cout << "Here is a very big number:/t" << 70000 << endl;
10:       cout << "Here is the sum of 8 and 5:/t" << 8+5 << endl;
11:       cout << "Here's a fraction:/t/t" << (float) 5/8 << endl;
12:       cout << "And a very very big number:/t" << (double) 7000 * 7000 <<endl;
13:       cout << "Don't forget to replace Jesse Liberty with your name.../n";
14:       cout << "Jesse Liberty is a C++ programmer!/n";
15:        return 0;
16: }

Hello there.
Here is 5: 5
The manipulator endl writes a new line to the screen.
Here is a very big number:      70000
Here is the sum of 8 and 5:     13
Here's a fraction:              0.625
And a very very big number:     4.9e+07
Don't forget to replace Jesse Liberty with your name...
Jesse Liberty is a C++ programmer!


On line 3, the statement #include <iostream.h> causes the iostream.h file to be added to your source code. This is required if you use cout and its related functions.

• 在第3行，语句#include <iostream.h> 导致 iostream.h 文件被添加到你的源代码中。如果你使用了cout和它的相关函数，需要这样做。

On line 6 is the simplest use of cout, printing a string or series of characters. The symbol /n is a special formatting character. It tells cout to print a newline character to the screen.

• 在第6行是cout的最简单的使用，打印一串字符。符号/n特殊格式符。它告诉cout在屏幕输出一个换行符。

Three values are passed to cout on line 7, and each value is separated by the insertion operator. The first value is the string "Here is 5: ". Note the space after the colon. The space is part of the string. Next, the value 5 is passed to the insertion operator and the newline character (always in double quotes or single quotes). This causes the line

• 在第7行传给了cout3个值，且每个值被插入操作符隔开。第一个值为字串："Here is 5:".注意冒号后面的空格。此空格为此串的一部分。接着，值5被传给了插入操作符再就是换行符（总是写在双引号或单引号里面）。这样会产生一个新行。

Here is 5: 5


to be printed to the screen. Because there is no newline character after the first string, the next value is printed immediately afterwards. This is called concatenating the two values.

• Here is 5: 5打印到屏幕。由于第1个字串后面没有换行符，所以下一个数值立即在后面打印。这被叫做连接两值。

On line 8, an informative message is printed, and then the manipulator endl is used. The purpose of endl is to write a new line to the screen. (Other uses for endl are discussed on Day 16.)

• 在第8行，一条信息被打印，然后使用了endl操作符。endl的目的就是把一个换行符写到屏幕（其他有关endl的使用将在第16天中讨论）。

On line 9, a new formatting character, /t, is introduced. This inserts a tab character and is used on lines 8-12 to line up the output. Line 9 shows that not only integers, but long integers as well can be printed. Line 10 demonstrates that cout will do simple addition. The value of 8+5 is passed to cout, but 13 is printed.

• 第9行中，引入一个新的格式符/t。这将插入一个tab符，第8-12行使用它是为了排列输出。第9行表明，不仅基本整型数，而且长整数也可被打印。第10行表明cout可以进行简单的加法运算。表达式8+5的值被传给cout，而打印出13。

On line 11, the value 5/8 is inserted into cout. The term (float) tells cout that you want this value evaluated as a decimal equivalent, and so a fraction is printed. On line 12 the value 7000 * 7000 is given to cout, and the term (double) is used to tell cout that you want this to be printed using scientific notation. All of this will be explained on Day 3, "Variables and Constants," when data types are discussed.

• 第11行，值5/8被插到流中。(float)是告诉cout你想使被计算的值成为它对应的小数，所以打印出一个小数。第12行中，值7000*7000被指定给cout，而(double)用来告诉cout你想以科学技术法形式打印。所有这些将在第3天的"变量和常量"里解释，到时候我们讨论数据类型。

On line 14, you substituted your name, and the output confirmed that you are indeed a C++ programmer. It must be true, because the computer said so!

• 第14行，你替换你自己的名字，程序输出被证实是：你确实是一个c++程序员。必须是真的，因为计算机说是啦。

### Comments注释

When you are writing a program, it is always clear and self-evident what you are trying to do. Funny thing, though--a month later, when you return to the program, it can be quite confusing and unclear. I'm not sure how that confusion creeps into your program, but it always does.

• 当你正在编程序时，总是试着使它清晰自明。有趣的是，即便如此--一个月以后，当你再回过头来看这个程序时，可能是非常不清楚而易糊涂的。我不能确定这种混乱是怎么跑到你的程序里的，可是却经常出现这些混乱。

To fight the onset of confusion, and to help others understand your code, you'll want to use comments. Comments are simply text that is ignored by the compiler, but that may inform the reader of what you are doing at any particular point in your program.

• 为应对这些混乱，为了帮助别人理解你的代码，需要你在程序中使用注释。注释仅仅是一些被编译器忽略的文本，但可以在你的程序的任意特定点处用来告诉读者你正在做什么。

#### Types of Comments注释的种类

C++ comments come in two flavors: the double-slash (//) comment, and the slash-star (/*) comment. The double-slash comment, which will be referred to as a C++-style comment, tells the compiler to ignore everything that follows this comment, until the end of the line.

• c++注释有两种形式：双斜线//和斜线-星/*注释。//注释是c++样式注释，告诉编译器忽略一切紧跟此注释符后的文本，直到行结束。

The slash-star comment mark tells the compiler to ignore everything that follows until it finds a star-slash (*/) comment mark. These marks will be referred to as C-style comments. Every /* must be matched with a closing */.

• /*注释标记告诉编译器忽略一切紧跟此符号后面的文本直到出现*/标记。这些标记归为c样式注释。每一个/*必须与一个*/成对出现。

As you might guess, C-style comments are used in the C language as well, but C++-style comments are not part of the official definition of C.

• 可能和你想得一样，c样式的注释也被用在c语言中，但是c++样式注释不是c的官方定义。

Many C++ programmers use the C++-style comment most of the time, and reserve C-style comments for blocking out large blocks of a program. You can include C++-style comments within a block "commented out" by C-style comments; everything, including the C++-style comments, is ignored between the C-style comment marks.

• 很多的c++的程序员很多时候使用c++式的注释，而保留c式的注释作为注释掉一大块程序来用。

#### Using Comments使用注释

As a general rule, the overall program should have comments at the beginning, telling you what the program does. Each function should also have comments explaining what the function does and what values it returns. Finally, any statement in your program that is obscure or less than obvious should be commented as well.

• 一般的规律，所有程序应该在开始有注释，告诉你程序干什么。每个函数也应该有注释来解释函数是干什么的和它返回什么值。最后，你程序的任何意思模糊或不太清晰的语句也应该被注释。

Listing 2.3 demonstrates the use of comments, showing that they do not affect the processing of the program or its output.

• 表2.3演示了注释的使用，表明它们并不会影响程序的进行和它的输出结果。

Listing 2.3. HELP.CPP demonstrates comments.

1: #include <iostream.h>
2:
3: int main()
4: {
5:  /* this is a comment
6:  and it extends until the closing
7:  star-slash comment mark */
8:    cout << "Hello World!/n";
9:    // this comment ends at the end of the line
10:   cout << "That comment ended!/n";
11:
12:  // double slash comments can be alone on a line
13: /* as can slash-star comments */
14:     return 0;
15: }
Hello World!
That comment ended!


The comments on lines 5 through 7 are completely ignored by the compiler, as
are the comments on lines 9, 12, and 13. The comment on line 9 ended with the
end of the line, however, while the comments on lines 5 and 13 required a closing comment mark.

• 第5-7行的注释会完全的被编译器所忽略，第9，12，13行的注释也同样被忽略。第9行注释在本行结束处结束。但第5和13行需要一个注释结束标记。

#### Comments at the Top of Each File每个文件开始处的注释

It is a good idea to put a comment block at the top of every file you write. The exact style of this block of comments is a matter of individual taste, but every such header should include at least the following information:

• 在你编写的每个代码文件开始放置一个注释快是一个好主意。代码块具体形式存粹因个人喜好，但是每个开头至少应包含下面的信息：

• The name of the function or program.
• 程序或者函数的名字

• The name of the file.
• 文件名

• What the function or program does.
• 函数或程序的功能

• A description of how the program works.
• 描述程序如何工作

• The author's name.
• 作者的名字

• A revision history (notes on each change made).
• 版本历史（注明每次的更改）

• What compilers, linkers, and other tools were used to make the program.
• 生成此程序所使用的编译器、连接器和其他工具

• Additional notes as needed.
• 所需的额外注解

For example, the following block of comments might appear at the top of the Hello World program.

/************************************************************

Program:      Hello World

File:         Hello.cpp

Function:     Main (complete program listing in this file)

Description:  Prints the words "Hello world" to the screen

Author:       Jesse Liberty (jl)

Environment:  Turbo C++ version 4, 486/66 32mb RAM, Windows 3.1
DOS 6.0.  EasyWin module.

Notes:        This is an introductory, sample program.

Revisions:    1.00  10/1/94 (jl) First release
1.01  10/2/94 (jl) Capitalized "World"

************************************************************/


It is very important that you keep the notes and descriptions up-to-date. A common problem with headers like this is that they are neglected after their initial creation, and over time they become increasingly misleading. When properly maintained, however, they can be an invaluable guide to the overall program.

• 不断更新你的注释和描述非常重要。这样的文件头一个普遍的问题就是，第一次创建以后就被忽视了，随着时间的推移，变得使人误解。但是适当的维护，可以成为整个程序无价的指南。

The listings in the rest of this book will leave off the headings in an attempt to save room. That does not diminish their importance, however, so they will appear in the programs provided at the end of each week.

• 在本书其余的表里都省掉了头以便节省空间。但那并不是因它不重要，所以，在每周结束所提供的程序都出现了注释头。

#### A Final Word of Caution About Comments关于注释的几点警告

Comments that state the obvious are less than useful. In fact, they can be counterproductive, because the code may change and the programmer may neglect to update the comment. What is obvious to one person may be obscure to another, however, so judgment is required.

• 陈诉自明的代码毫无用处。事实上，可能适得其反，因为代码也许变化而程序员可能忽略了更新注释。但是一个人看来是明了的对别人来说或许是不清晰的，所以呢应该有适当的判断。

The bottom line is that comments should not say what is happening, they should say why it is happening.

• 最后，注释不应当是说正发生什么而应说为什么发生。

DO add comments to your code. DO keep comments up-to-date. DO use comments to tell what a section of code does. DON'T use comments for self-explanatory code.
• 做：给你的代码添加代码；保持你的注释最新；用注释告诉一段代码是干什么的。
• 不做：用注释说明本身就已经很明了的代码。

### Functions函数

While main() is a function, it is an unusual one. Typical functions are called, or invoked, during the course of your program. A program is executed line by line in the order it appears in your source code, until a function is reached. Then the program branches off to execute the function. When the function finishes, it returns control to the line of code immediately following the call to the function.

• 说main()是一个函数吧，可是它又有不同之处。函数在程序运行期间被调用。一个程序按照他在源代码中所出现的程序一行一行的执行，直到碰到一个函数。然后程序转到函数里面去执行。当函数执行完成时，它会立即返回到主调函数调用处继续执行。

A good analogy for this is sharpening your pencil. If you are drawing a picture, and your pencil breaks, you might stop drawing, go sharpen the pencil, and then return to what you were doing. When a program needs a service performed, it can call a function to perform the service and then pick up where it left off when the function is finished running. Listing 2.4 demonstrates this idea.

• 一个好的比方是你削铅笔。如果你正在画一幅画，而你的铅笔断了，你或许停止绘画，转去削铅笔，然后返回去做你正做的事情。当一个程序要执行一项服务，它可以去调用一个函数执行这个服务，当函数完成后返回到调用处。表2.4演示这种思想。

Listing 2.4. Demonstrating a call to a function. 演示一个函数的调用。

1:     #include <iostream.h>
2:
3:     // function Demonstration Function
4:     // prints out a useful message
5:     void DemonstrationFunction()
6:     {
7:         cout << "In Demonstration Function/n";
8:     }
9:
10:    // function main - prints out a message, then
11:    // calls DemonstrationFunction, then prints out
12:    // a second message.
13:    int main()
14:    {
15:        cout << "In main/n" ;
16:        DemonstrationFunction();
17:        cout << "Back in main/n";
18:         return 0;
19: }
In main
In Demonstration Function
Back in main


The function DemonstrationFunction() is defined on lines 5-7. When it is called, it prints a message to the screen and then returns.

• 函数DemonstrationFunction() 在第5-7行定义。当调用它时，它会在屏幕上打印一条信息，然后返回。

Line 13 is the beginning of the actual program. On line 15, main() prints out a message saying it is in main(). After printing the message, line 16 calls DemonstrationFunction(). This call causes the commands in DemonstrationFunction() to execute. In this case, the entire function consists of the code on line 7, which prints another message. When DemonstrationFunction() completes (line 8), it returns back to where it was called from. In this case the program returns to line 17, where main() prints its final line.

• 第13行是实际程序的开始。第15行，main()打印一条消息说明正处在main()中。在打印这条之后，第16行调用DemonstrationFunction()。此调用导致执行DemonstrationFunction()函数。本例中，整个函数由第7行组成，它会打印另一条信息。当DemonstrationFunction()函数执行完以后（第8行），它会返回到调用处，本例中返回到第17行，在那里main()输出最后一行。

#### Using Functions使用函数

Functions either return a value or they return void, meaning they return nothing. A function that adds two integers might return the sum, and thus would be defined to return an integer value. A function that just prints a message has nothing to return and would be declared to return void.

• 函数要么返回一个值，要么返回void(意味着什么也不返回）。一个对两整数求和的函数或许返回和数，这样可以把函数定义为返回一个整型值。一个只打印一条消息的函数什么也不返回，可以被定义为返回void。

Functions consist of a header and a body. The header consists, in turn, of the return type, the function name, and the parameters to that function. The parameters to a function allow values to be passed into the function. Thus, if the function were to add two numbers, the numbers would be the parameters to the function. Here's a typical function header:

• 函数由头部分和体部分组成。头部分包括函数返回值类型，函数名字和函数的参数。函数的参数允许把值传给函数。这样，如果函数是用来加两个数，这两个数就是函数的参数。这里是一个函数的头部：

int Sum(int a, int b)


A parameter is a declaration of what type of value will be passed in; the actual value passed in by the calling function is called the argument. Many programmers use these two terms, parameters and arguments, as synonyms. Others are careful about the technical distinction. This book will use the terms interchangeably.

• 形式参数是对要传入的值的声明；调用函数传入的实际值叫做实参。很多程序员把这两个术语视为同义字。有些则区别两词。本书中，两者可交替使用。

The body of a function consists of an opening brace, zero or more statements, and a closing brace. The statements constitute the work of the function. A function may return a value, using a return statement. This statement will also cause the function to exit. If you don't put a return statement into your function, it will automatically return void at the end of the function. The value returned must be of the type declared in the function header.

• 函数体则由一个开大括号{，0个或更多的语句，还有一个闭大括号}组成。语句使得函数能执行某项操作。函数可以返回一个值，通过使用返回语句。这个语句也使得退出函数。如果你不在你的函数中加入return 语句，它会自动在函数结束时返回void.被返回的值必须是函数头部所声明的类型。

NOTE: Functions are covered in more detail on Day 5, "Functions." The types that can be returned from a function are covered in more det+[radical][Delta][infinity]on Day 3. The information provided today is to present you with an overview, because functions will be used in almost all of your C++ programs.
在第5天"函数"中将更详细的探讨函数。关于函数返回值类型将在第3天中详细探讨。今天所提供的信息仅是给你提供一个总览，因为函数将在几乎所有的c++程序中使用。

Listing 2.5 demonstrates a function that takes two integer parameters and returns an integer value. Don't worry about the syntax or the specifics of how to work with integer values (for example, int x) for now; that is covered in detail on Day 3.

• 表2.5演示一个带有两个整型参数和返回一个整型值的函数。现在先不用关心语法或者整数（例如int x）如何工作的细节问题，这将在第3天讨论。

Listing 2.5. FUNC.CPP demonstrates a simple function. 演示一个简单的函数

1:    #include <iostream.h>
2:    int Add (int x, int y)
3:    {
4:
5:      cout << "In Add(), received " << x << " and " << y << "/n";
6:      return (x+y);
7:    }
8:
9:    int main()
10:    {
11:         cout << "I'm in main()!/n";
12:         int a, b, c;
13:         cout << "Enter two numbers: ";
14:         cin >> a;
15:         cin >> b;
16:         cout << "/nCalling Add()/n";
17:         c=Add(a,b);
18:         cout << "/nBack in main()./n";
19:         cout << "c was set to " << c;
20:         cout << "/nExiting.../n/n";
21:         return 0;
22: }

I'm in main()!
Enter two numbers: 3 5

Calling Add()
In Add(), received 3 and 5

Back in main().
c was set to 8

Exiting...


The function Add() is defined on line 2. It takes two integer parameters and returns an integer value. The program itself begins on line 9 and on line 11, where it prints a message. The program prompts the user for two numbers (lines 13 to 15). The user types each number, separated by a space, and then presses the Enter key. main() passes the two numbers typed in by the user as arguments to the Add() function on line 17.

• 函数add()在第2行定义。它带2个参数并返回一个整数。程序本身在第9行开始，在第11行打印一条信息。在第13——15行提示用户输2个数。用户用空格隔开每个数，然后按回车键。在17行main()函数把用户输入的两个数作为实参传给add()函数。

Processing branches to the Add() function, which starts on line 2. The parameters a and b are printed and then added together. The result is returned on line 6, and the function returns.

• 程序转到第二行定义的add()函数。参数a和b被打印，然后加在一起。结果在第6行被返回，然后函数返回主调函数。

In lines 14 and 15, the cin object is used to obtain a number for the variables a and b, and cout is used to write the values to the screen. Variables and other aspects of this program are explored in depth in the next few days.

• 在14行和15行，cin对象被用来为变量a和b得到一个数，而cout用来把值写到屏幕。变量和本程序其它部分将在后面几天深入地剖析。

### Summary总结

The difficulty in learning a complex subject, such as programming, is that so much of what you learn depends on everything else there is to learn. This chapter introduced the basic
parts of a simple C++ program. It also introduced the development cycle and a number of important new terms.

• 学习复杂科目如编程的难点在于，你所学的东西还要依赖于其他要学的东西。这一章介绍一个简单程序的基本部分。也同时引入了开发周期和许多重要的新术语。

### Q&A问&答

Q. What does #include do?
#include 用来干什么？

A. This is a directive to the preprocessor, which runs when you call your compiler. This specific directive causes the file named after the word include to be read in, as if it were typed in at that location in your source code.
这是给预处理器的一个指示，当你调用编译器的时候运行。这个特殊指令使得紧接include 后面的文件被读入，就好像在源文件此处位置亲手键入一样。

Q. What is the difference between // comments and /* style comments?
//注释和/*注释什么区别？

A. The double-slash comments (//) "expire" at the end of the line. Slash-star (/*) comments are in effect until a closing comment (*/). Remember, not even the end of the function terminates a slash-star comment; you must put in the closing comment mark, or you will get a compile-time error.

Q. What differentiates a good comment from a bad comment?
如何区别一个好的注释与不好的注释？

A. A good comment tells the reader why this particular code is doing whatever it is doing or explains what a section of code is about to do. A bad comment restates what a particular line of code is doing. Lines of code should be written so that they speak for themselves. Reading the line of code should tell you what it is doing without needing a comment.
好的注释告诉读者，特定代码为什么要这样做或者解释一段代码要做什么。不好的注释则是重述一段代码做什么。这些行代码应当让它们自己阐明自己功能。读这行代码时就应当告诉你它的功能而无需注释。

### Workshop

The Workshop provides quiz questions to help you solidify your understanding of the material covered and exercises to provide you with experience in using what you've learned. Try to answer the quiz and exercise questions before checking the answers in Appendix D, and make sure you understand the answers before continuing to the next chapter.

• workshop部分为你提供了一些测验题 以帮助你巩固对书中知识点理解，还提供了练习供你对所学的知识更多认识。在核对附录D中答案前尝试回答测验和练习问题，在继续下一章前确保你已经理解所有答案。

#### Quiz测验

1. What is the difference between the compiler and the preprocessor?
编译器和预处理器有什么区别？

2.
Why is the function main() special?
main()函数有什么特殊之处？

3.
What are the two types of comments, and how do they differ?
c++中有哪两种注释类型，有什么区别？

4
. Can comments be nested?
注释可以嵌套么？

5.
Can comments be longer than one line?
注释长度能超过一行么？

#### Exercises练习

1. Write a program that writes I love C++ to the screen.
编写一个程序在屏幕中输出：I love C++

2.
Write the smallest program that can be compiled, linked, and run.
编写最小的可以编译、连接并运行的程序。

3.
BUG BUSTERS: Enter this program and compile it. Why does it fail? How can you fix it?
改错：键入这个程序并编译一下。为什么不能通过？你能改正它么？

1: #include <iostream.h>
2: void main()
3: {
4: cout << Is there a bug here?";
5: }


4. Fix the bug in Exercise 3 and recompile, link, and run it.
改正练习3的错误，重新编译，连接运行一下。

•
• 0
0
查看评论
* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：4729次
• 积分：108
• 等级：
• 排名：千里之外
• 原创：1篇
• 转载：0篇
• 译文：1篇
• 评论：1条
文章分类
文章存档
阅读排行
最新评论