Microsoft Visual C++ Windows Applications by Example phần 2 doc

43 327 0
Microsoft Visual C++ Windows Applications by Example phần 2 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Introduction to C++ [ 28 ] In the examples above, it is not strictly necessary to surround the output statements with brackets. However, it would be necessary in the case of several statements. In this book, brackets are always used. The brackets and the code in between is called a block. if (i > 0) { int j = i + 1; cout << "j is " << j; } A warning may be in order. In an if statement, it is perfectly legal to use one equals sign instead of two when comparing two values. As one equals sign is used for assignment, not comparison, the variable i in the following code will be assigned the value one, and the expression will always be true. if (i = 1) // Always true. { // } One way to avoid the mistake is to swap the variable and the value. As a value can be compared but not assigned, the compiler will issue an error message if you by mistake enter one equals sign instead of two signs. if (1 = i) // Compile-time error. { // } The switch statement is simpler than the if statement, and not as powerful. It evaluates the switch value and jumps to a case statement with the same value. If no value matches, it jumps to the default statement, if present. It is important to remember the break statement. Otherwise, the execution would simply continue with the code attached to the next case statement. The break statement is used to jump out of a switch or iteration statement. The switch expression must have an integral or pointer type and two case statements cannot have the same value. The default statement can be omitted, and we can only have one default alternative. However, it must not be placed at the end of the switch statement, even though it is considered good practice to do so. switch (i) { case 1: cout << "i is equal to 1" << endl; break; Chapter 1 [ 29 ] case 2: cout << "i is equal to 2" << endl; break; case 3: cout << "i is equal to 3" << endl; int j = i + 1; cout << "j = " << j; break; default: cout << "i is not equal to 1, 2, or 3." << endl; break; } In the code above, there will be a warning for the introduction of the variable j. As a variable is valid only in its closest surrounding scope, the following code below will work without the warning. switch (i) { // case 3: cout << "i is equal to 3" << endl; { int j = i + 1; cout << "j = " << j; } break; // } We can use the fact that an omitted break statement makes the execution continue with the next statement to group several case statements together. switch (i) { case 1: case 2: case 3: cout << "i is equal to 1, 2, or 3" << endl; break; // } Introduction to C++ [ 30 ] Iteration Statements Iteration statements iterate one statement (or several statements inside a block) as long as certain condition is true. The simplest iteration statement is the while statement. It repeats the statement as long as the given expression is true. The example below writes the numbers 1 to 10. int i = 1; while (i <= 10) { cout << i; ++i; } The same thing can be done with a do-while statement. int i = 1; do { cout << i; ++i; } while (i <= 10); The do-while statement is less powerful. If the expression is false at the beginning, the while statement just skips the repetitions altogether, but the do-while statement must always execute the repetition statement at least once in order to reach the continuation condition. We can also use the for statement, which is a more compact variant of the while statement. It takes three expressions, separated by semicolons. In the code below, the rst expression initializes the variable, the repetition continues as long as the second expression is true, and the third expression is executed at the end of each repetition. for (int i = 1; i <= 10; ++i) { cout << i; } Similar to the switch statement, the iteration statements can be interrupted by the break statement. int i = 1; while (true) { cout << i; ++i; Chapter 1 [ 31 ] if (i > 10) { break; } } Another way to construct an eternal loop is to omit the second expression of a for statement. for (int i = 1; ; ++i) { cout << i; if (i > 10) { break; } } An iteration statement can also include a continue statement. It skips the rest of the current repetition. The following example writes the numbers 1 to 10 with the exception of 5. for (int i = 1; i <= 10; ++i) { if (i == 5) { continue; } cout << i; } The following example, however, will not work. Because the continue statement will skip the rest of the while block, i will never be updated, and we will be stuck inwill never be updated, and we will be stuck in an innite loop. Therefore, I suggest you use the continue statement with care. int i = 1; while (i <= 10) { if (i == 5) { continue; } cout << i; ++i; } Introduction to C++ [ 32 ] Jump Statements We can jump from one location to another inside the same function block by marking the latter location with a label inside the block with the goto statement. int i = 1; label: cout << i; ++ i; if (i <= 10) { goto label; } The goto statement is, however, considered to give rise to unstructured code, so called "spaghetti code". I strongly recommend that you avoid the goto statement altogether. Expression Statements An expression can form a statement. a = b + 1; // Assignment operator. cout << "Hello, World!"; // Stream operator. WriteNumber(5); // Function call. In the above examples, we are only interested in the side effects; that a is assigned a new value or that a text or a number is written. We are allowed to write expression statements without side effects; even though it has no meaning and it will probably be erased by the compiler. a + b * c; Functions A function can be compared to a black box. We send in information (input) and we receive information (output). In C++, the input values are called parameters and the output value is called a return value. The parameters can hold every type, and the return value can hold every type except the array. Chapter 1 [ 33 ] To start with, let us try the function Square. This function takes an integer and returns its square. int Square(int n) { return n * n; } void main() { int i = Square(3); // Square returns 9. } In the example above, the parameter n in Square is called a formal parameter, and the value 3 in Square called in main is called an actual parameter. Let us try a more complicated function, SquareRoot takes a value of double type and returns its square root. The idea is that the function iterates and calculates increasingly better root values by taking the mean value of the original value divided with the current root value and the previous root value. The process continues until the difference between two consecutive root values has reached an acceptable tolerance. Just like main, a function can have local variables. dRoot and dPrevRoot hold the current and previous value of the root, respectively. #include <iostream> using namespace std; double SquareRoot(double dValue) { const double EPSILON = 1e-12; double dRoot = dValue, dOldRoot = dValue; while (true) { dRoot = ((dValue / dRoot) + dRoot) / 2; cout << dRoot << endl; if ((dOldRoot - dRoot) <= EPSILON) { return dRoot; } dOldRoot = dRoot; } } Introduction to C++ [ 34 ] void main() { double dInput = 16; cout << "SquareRoot of " << dInput << ": " << SquareRoot(dInput) << endl; } Void Functions A function does not have to return a value. If it does not, we set void as the return type. As mentioned above, void is used to state the absence of a type rather than a type. We can return from a void function by just stating return without a value. void PrintSign(int iValue) { if (iValue < 0) { cout << "Negative."; return; } if (iValue > 0) { cout << "Positive."; return; } cout << "Zero"; } There is no problem if the execution of a void function reaches the end of the code, it just jumps back to the calling function. However, a non-void function shall always return a value before reaching the end of the code. The compiler will give a warning if it is possible to reach the end of a non-void function. Local and Global Variables There are four kinds of variables. Two of them are local and global variables, which we consider in this section. The other two kinds of variables are class elds and exceptions, which will be dealt with in the class and exception sections of the next chapter. Chapter 1 [ 35 ] A global variable is dened outside a function and a local variable is dened inside a function. int iGlobal = 1; void main() { int iLocal = 2; cout << "Global variable: " << iGlobal // 1 << ", Local variable: " << iLocal // 2 << endl; } A global and a local variable can have the same name. In that case, the name in the function refers to the local variable. We can access the global variable by using two colons (::). int iNumber = 1; void main() { int iNumber = 2; cout << "Global variable: " << ::iNumber // 1 << ", Local variable: " << iNumber; // 2 } A variable can also be dened in an inner block. As a block may contain another block, there may be many variables with the same name in the same scope. Unfortunately, we can only access the global and the most local variable. In the inner block of the following code, there is no way to access iNumber with value 2. int iNumber = 1; void main() { int iNumber = 2; { int iNumber = 3; cout << "Global variable: " << ::iNumber // 1 << ", Local variable: " << iNumber; // 3 } } Introduction to C++ [ 36 ] Global variables are often preceded by g_ in order to distinguish them from local variables. int g_iNumber = 1; void main() { int iNumber = 2; cout << "Global variable: " << g_iNumber // 1 << ", Local variable: " << iNumber; // 3 } Call-by-Value and Call-by-Reference Say that we want to write a function for switching the values of two variables. #include <iostream> using namespace std; void Swap(int iNumber1, int iNumber2) { int iTemp = iNumber1; // (a) iNumber1 = iNumber2; // (b) iNumber2 = iTemp; // (c) } void main() { int iNum1 = 1, iNum2 = 2; cout << "Before: " << iNum1 << ", " << iNum2 << endl; Swap(iNum1, iNum2); cout << "After: " << iNum1 << ", " << iNum2 << endl; } Unfortunately, this will not work; the variables will keep their values. The explanation is that the values of iFirstNum and iSecondNum in main are copied into iNum1 and iNum2 in Swap. Then iNum1 and iNum2 exchange values with the help if iTemp. However, their values are not copied back into iFirstNum and iSecondNum in main. Chapter 1 [ 37 ] The problem can be solved with reference calls. Instead of sending the values of the actual parameters, we send their addresses by adding an ampersand (&) to the type. As you can see in the code, the Swap call in main is identical to the previous one without references. However, the call will be different. #include <iostream> using namespace std; void Swap(int& iNum1, int& iNum2) { int iTemp = iNum1; // (a) iNum1 = iNum2; // (b) iNum2 = iTemp; // (c) } void main() { int iFirstNum = 1, iSecondNum = 2; cout << "Before: " << iFirstNum << ", " << iSecondNum << endl; Swap(iFirstNum, iSecondNum); cout << "After: " << iFirstNum << ", " << iSecondNum << endl; } [...]... \Ö 118 v 15 si 41 ) 67 C 93 ]Å 119 w 16 dle 42 * 68 D 94 ^Ü 120 x 17 dc1 43 + 69 E 95 _ 121 y 18 dc2 44 , 70 F 96 `é 122 z 19 dc3 45 - 71 G 97 a 123 {ä 20 dc4 46 72 H 98 b 124 |ö 21 nak 47 / 73 I 99 c 125 }å 22 syn 48 0 74 J 100 d 126 ~ü 23 etb 49 1 75 K 101 e 127 delete 24 can 50 2 76 L 1 02 f 25 em 51 3 77 M 103 g [ 47 ] Introduction to C++ Summary Let's revise the points quickly in brief as discussed... . w 16 dle 42 * 68 D 94 ^ Ü 120 x 17 dc1 43 + 69 E 95 _ 121 y 18 dc2 44 , 70 F 96 ` é 122 z 19 dc3 45 - 71 G 97 a 123 { ä 20 dc4 46 . 72 H 98 b 124 | ö 21 nak 47 / 73 I 99 c 125 } å 22 syn 48 0. Table 0 nul 26 sub 52 4 78 N 104 h 1 soh 27 esc 53 5 79 O 105 i 2 stx 28 fs 54 6 80 P 106 j 3 etx 29 gs 55 7 81 Q 107 k 4 eot 30 rs 56 8 82 R 108 l 5 enq 31 us 57 9 83 S 109 m 6 ack 32 blank 58. b 124 | ö 21 nak 47 / 73 I 99 c 125 } å 22 syn 48 0 74 J 100 d 126 ~ ü 23 etb 49 1 75 K 101 e 127 delete 24 can 50 2 76 L 1 02 f 25 em 51 3 77 M 103 g

Ngày đăng: 12/08/2014, 21:20

Từ khóa liên quan

Mục lục

  • Chapter 1: Introduction to C++

    • Statements

      • Iteration Statements

      • Jump Statements

      • Expression Statements

      • Functions

        • Void Functions

        • Local and Global Variables

        • Call-by-Value and Call-by-Reference

        • Default Parameters

        • Overloading

        • Static Variables

        • Recursion

        • Definition and Declaration

        • Higher Order Functions

        • The main() Function

        • The Preprocessor

        • The ASCII Table

        • Summary

        • Chapter 2: Object-Oriented Programming in C++

          • The Object-Oriented Model

          • Classes

            • The First Example

            • The Second Example

            • Inheritance

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan