1. Trang chủ
  2. » Công Nghệ Thông Tin

Teach Yourself Visual C++ 6 in21 Days phần 8 potx

80 212 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 80
Dung lượng 443,57 KB

Nội dung

APPENDIX A C++ Review The appendix is designed to provide you with a quick review of the fundamen- tals of the C++ programming language. After reading this appendix, you will have a thorough understanding of the various aspects of C++ and its syntax. Creating Your First Application Your first example is a simple program that displays “Hello World” on the screen. For this, you create a workspace and the C++ file required for the pro- gram. The procedure for writing a C++ program using Visual C++ is simple and easy. Follow these steps: 1. From the main menu, select Visual C++. 2. Select File | New from the Visual C++ toolbar. Make sure the Projects tab is selected (see Figure A.1). 3. Select Win32 Console Application from the options on the left. 029 31240-9 App A 4/27/00 1:06 PM Page 541 4. Type Hello on the right side under Project Name. 5. Select OK. Visual C++ creates the workspace of your application. Visual C++ actually creates a directory Hello, which enables you to store all files related to a particular project in one area. You will begin adding the files you require for this project: 1. Once again, select File | New from the toolbar. 2. Select the Files tab if it is not already selected. 3. Highlight C++ Source File. 4. Check the Add to Project box on the right side. 5. In the File Name edit box, type Helloworld (see Figure A.2). 6. Click OK. 542 Appendix A FIGURE A.1. Setting up the Hello workspace. FIGURE A.2. Setting up the Helloworld project. 029 31240-9 App A 4/27/00 1:06 PM Page 542 C++ Review 543 A The Helloworld.cpp file is where you add the C++ source code. All C++ source code files have a .cpp extension. Later, I will cover other file types. You create all the tutorial examples in this section in a similar way. The only difference is that the names of the workspaces and the files are different. Helloworld.cpp The Helloworld program displays HELLO WORLD on the screen. Listing A.1 contains the code. Type the code exactly as shown in the Helloworld.cpp window. Do not type the line numbers; they are for reference only. C++ is case sensitive, so main is not the same as MAIN, which is not the same as Main. LISTING A.1. Helloworld.cpp. 1: // Workspace Name: Hello 2: // Program Name: Helloworld.cpp 3: 4: # include <iostream.h> 5: 6: int main() 7: 8: { 9: cout<< “HELLO WORLD \n”; 10: return 0; 11: } To run the program, follow these steps: 1. Select File | Save to save your work. 2. Select Build | Set Active Configuration (see Figure A.3). 3. Highlight Hello - Win32 Debug and click OK (see Figure A.4). 4. Select Build | Build Hello.exe. Visual C++ compiles and links the program to create an executable file. The configura- tion window indicates the success or failure of the compilation. A successful compilation returns Hello.exe - 0 error(s), 0 warning(s) If you encounter any errors, verify that all the lines of the program were typed exactly as shown. To execute the Helloworld program, select Build|Execute Hello.exe. 029 31240-9 App A 4/27/00 1:06 PM Page 543 544 Appendix A FIGURE A.3. Setting the active con- figuration. FIGURE A.4. Selecting Win32 Debug. The program executes by opening an MS-DOS shell and displaying the text HELLO WORLD (see Figure A.5). FIGURE A.5. HELLO WORLD display. 029 31240-9 App A 4/27/00 1:06 PM Page 544 C++ Review 545 A Components of Helloworld.cpp The first two lines of the program are comment lines: // Workspace Name: Hello // Program Name: Helloworld.cpp The double slash command (//) tells the compiler to ignore everything after the slash. It is good programming practice to comment your work because it makes the program easi- er to read, especially for someone who did not write it. Comments become important when you are working on a complex program for months. When you want to make changes, comments assist you in recollecting your thoughts from more than a month ago. The third line begins with the pound symbol (#): # include <iostream.h> This is a directive to the preprocessor to search for the filename that follows (iostream.h) and include it. The angled brackets (<>) cause the preprocessor to search for the file in the default directories. The iostream.h file contains definitions for the insertion (<<) and extraction (>>) operators. This directive is required to process the cout statement defined on line 9 in the program. The iostream.h file is a precompiled header provided with your compiler. You may experiment with the Helloworld program by com- menting out the include line. To do this, insert the backslash (//) before the pound sign (#). When you compile and execute this program, you get an error: Compiling Helloworld.cpp C:\cplusplus\Hello\Helloworld.cpp(9) : error C2065: ➥ ‘cout’ : undeclared identifier C:\cplusplus\Hello\Helloworld.cpp(9) : error C2297: ‘<<’ : bad right ➥operand Error executing cl.exe. Hello.exe - 2 error(s), 0 warning(s) Without the iostream.h file, the program does not recognize the cout command or the insertion operator (<<). The next line of code, line 6, is actually where program execution begins. This is the entry point of your code: int main() This line tells the compiler to process a function named main. Every C++ program is a collection of functions. You will cover functions in greater detail later in this appendix. For now, you define a function as the entry point for a block of code with a given name. The empty parentheses indicate that the function does not pass any parameters. Passing 029 31240-9 App A 4/27/00 1:06 PM Page 545 parameters by functions is described in the section “Functions and Variables,” later in this chapter. Every C++ program must have the function main(). It is the entry point to begin pro- gram execution. If a function returns a value, its name must be preceded by the type of value it will return; in this case, main() returns a value of type int. The block of code defined by any function should be enclosed in curly brackets ({}): { cout<< “HELLO WORLD \n”; return 0; } All code within these brackets belongs to the named function—in this case, main(). The next line executes the cout object. It is followed by the redirection operator <<, which passes the information to be displayed. The text to be displayed is enclosed in quotes. This is followed by the newline operator (\n). The redirection or insertion opera- tor (<<) tells the code that whatever follows is to be inserted to cout. 546 Appendix A Line 9 ends with a semicolon. All statements in C++ must end with a semi- colon. Note Line 10 of the code has a return statement. Programmers often use return statements either to return certain values or to return errors. Also remember that on line 7 when you defined the main() function, you defined its return type to be an integer (int). You may rerun this code by deleting the return statement on line 10, in which case line 7 would have to be modified as follows: void main() It is good programming practice to include return codes for complex programs. They will help you identify and track down bugs in your program. Functions and Variables The Helloworld program consists of only one function, main(). A functional C++ pro- gram typically consists of more than a single function. To use a function, you must first declare it. A function declaration is also called its prototype. A prototype is a concise representation of the entire function. When you prototype a function, you are actually 029 31240-9 App A 4/27/00 1:06 PM Page 546 C++ Review 547 A writing a statement, and as mentioned before, all statements in C++ should end with semicolons. A function prototype consists of a return type, name, and parameter list. The return type in the main() function is int, the name is main, and the parameter list is (), null. A function must have a prototype and a definition. The prototype and the definition of a function must agree in terms of return type, name, and parameter list. The only differ- ence is that the prototype is a statement and must end with a semicolon. Listing A.2 illustrates this point with a simple program to calculate the area of a triangle. LISTING A.2. Area.cpp. 1: // Workspace: Triangle 2: // Program name: Area.cpp 3: // The area of a triangle is half its base times height 4: // Area of triangle = (Base length of triangle * Height of triangle)/2 5: 6: #include <iostream.h> // Precompiled header 7: 8: double base,height,area; // Declaring the variables 9: double Area(double,double); // Function Prototype/declaration 10: 11: int main() 12: { 13: cout << “Enter Height of Triangle: “; // Enter a number 14: cin >> height; // Store the input in variable 15: cout << “Enter Base of Triangle: “; // Enter a number 16: cin >> base; // Store the input in variable 17: 18: area = Area(base,height); // Store the result from the Area ➥function 19: // in the variable area 20: cout << “The Area of the Triangle is: “<< area << endl ; // Output the ➥area 21: 22: return 0; 23: } 24: 25: double Area (double base, double height) // Function definition 26: { 27: area = (0.5*base*height); 28: return area; 29: } This program declares three variables, base, height, and area, on line 8. Variables store values that are used by the program. The type of a variable specifies the values to be stored in the variable. Table A.1 shows the various types supported by C++. 029 31240-9 App A 4/27/00 1:06 PM Page 547 TABLE A.1. VARIABLE DATA TYPES. Variable Data Type Values unsigned short int 0 to 65,535 short int –32,768 to 32,767 unsigned long int 0 to 4,294,967,925 long int –2,147,483,648 to 2,147,483,647 int –2,147,483,648 to 2,147,483,647 (32 bit) unsigned int 0 to 4,294,967,295 (32 bit) char 256 character values float 1.2e–38 to 3.4e38 double 2.2e–308 to 1.8e308 To define a variable, you first define its type, followed by the name. You may also assign values to variables by using the assignment (=) operator, as in these two examples: double base = 5; unsigned long int base =5; In C++, you may also define your own type definition. You do this by using the keyword typedef, followed by the existing type and name: typedef unsigned long int ULONG; ULONG base =5; Defining your own type does save you the trouble of typing the entire declaration. The next line of the code, line 9, defines the prototype of your function: double Area (double,double); This function has a type double, a name Area, and a parameter list of two variables of type double. When you define the prototype, it is not necessary to define the parameters, but it is a good practice to do so. This program takes two inputs from the user, namely base and height of the triangle, and calculates the area of the triangle. The base, height, and area are all variables. The Helloworld.cpp example used the insertion (<<) operator. In this example, you use the extraction (>>) operator. The program queries the user to enter a value for the height of the triangle on line 13. When the user enters a value for height, the data from the screen is extracted and placed into the variable height. The process is repeated for the base of the triangle on lines 15 and 16. After 548 Appendix A 029 31240-9 App A 4/27/00 1:06 PM Page 548 C++ Review 549 A accepting the input from the user, the function main() passes execution to the function Area(base,height) along with the parameter values for base and height. When main() passes the execution to the function Area(base, height), it expects a value of type double in return from the function. The calculation of the area of the triangle is conducted on line 27: area = (0.5*base*height); Area is the name of a function, and area is a variable name. Because C++ is case sensitive, it clearly distinguishes these two names. Note This statement uses the standard operators, the assignment operator (=), and the multipli- cation operator (*). The assignment operator assigns the result of (0.5*base*height) to the variable area. The multiplication operator (*) calculates the resulting values of (0.5*base*height). The assignment operator (=) has an evaluation order from right-to- left. Hence, the multiplication is carried out prior to assigning the values to area. The five basic mathematical operators are addition (+), subtraction (–), multiplication (*), division (/), and modulus (%). Line 28 of the Area function returns the value of the variable area to the main() func- tion. At this point, the control of the program is returned to line 18 of the main() func- tion. The remainder of the program displays the result of area to the screen. The if Statement, Operators, and Polymorphism While programming large complex programs, it is often necessary to query the user and provide direction to the program based on his input. This is accomplished by using the if statement. The next example demonstrates the application of an if statement. The format of the if statement is if (this expression) do this; The if statement is often used in conjunction with relational operators. Another format of the if statement is if (this expression) do this; else do this; Because if statements often use relational operators, let’s review relational operators. Relational operators are used to determine if two expressions or numbers are equal. If 029 31240-9 App A 4/27/00 1:06 PM Page 549 the two expressions or numbers are not equal, the statement will evaluate to either 0 or false. Table A.2 lists the six relational operators defined in C++. TABLE A.2. RELATIONAL OPERATORS. Operator Name == Comparative != Not equal > Greater than < Less than >= Greater than or equal to <= Less than or equal to C++ also has logical operators. The advantage of logical operators is the ability to com- pare two individual expressions and conclude whether they are true or false. Table A.3 lists the three logical operators. TABLE A.3. LOGICAL OPERATORS. Symbol Operator && AND || OR ! NOT An important and powerful feature of C++ is function overloading, or polymorphism. Polymorphism is the ability to have more than one function with the same name that dif- fer in their parameter lists. The next example is an extension of the previous triangle code. In this program, you will calculate the area of a triangle and a circle. You will be asked whether you want to calculate the area of a triangle or a circle. Depending upon your response, 1 for triangle and 2 for circle, the program collects your input and calcu- lates the area. In Listing A.3, the Area function is overloaded. The same function name is used to calculate the area of the triangle or the circle. The functions differ only in their parameter lists. LISTING A.3. Overload.ccp. 1: // Workspace Name: Overload 2: // Program Name: Overload.cpp 3: 4: # include <iostream.h> 5: 550 Appendix A 029 31240-9 App A 4/27/00 1:06 PM Page 550 [...]... 5: 6: 7: 8: 9: 10: 11: // Workspace: Class2 // Program Name: Clasfarm.hpp #include class farm_house { int pig_values; public: void set(int input); int get(void); }; 565 A 029 31240-9 App A 4/27/00 1: 06 PM Page 566 566 Appendix A The Clasfarm.cpp file is in Listing A.11 LISTING A.11 Clasfarm.cpp 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: ... Workspace Name: Class3 2: // Program Name: Class3.cpp 3: #include 029 31240-9 App A 4/27/00 1: 06 PM Page 567 C++ Review 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: class Tax_assessment { int city_tax; int prop_tax; public: void set(int in_city,...029 31240-9 App A 4/27/00 1: 06 PM Page 551 C++ Review 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 551 double base,height,radius; // Global variables double Area_of_triangle,Area_of_circle;... create the objects of type human and access its data and functions 569 A 029 31240-9 App A 4/27/00 1: 06 PM Page 570 570 Appendix A LISTING A.13 Inherit1.cpp 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: // Workspace Name: Inherit // Program Name : Inherit1.cpp #include... private 561 A 029 31240-9 App A 4/27/00 1: 06 PM Page 562 562 Appendix A You will now re-create the previous example of Struct.cpp in Listing A .8, employing the class and encapsulation methodology The output from this program in Listing A.9 is identical to the previous example, Struct.cpp LISTING A.9 Clasfarm.cpp 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: ... variable in the main() function LISTING A.7 Refer.cpp 1: 2: 3: 4: 5: 6: 7: 8: // Workspace: Reference // Program name: Refer.cpp #include void squareit (float &num); int main() continues A 029 31240-9 App A 4/27/00 1: 06 PM Page 5 58 5 58 Appendix A LISTING A.7 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: CONTINUED { float num=5.0; cout . 4,294, 967 ,925 long int –2,147, 483 ,64 8 to 2,147, 483 ,64 7 int –2,147, 483 ,64 8 to 2,147, 483 ,64 7 (32 bit) unsigned int 0 to 4,294, 967 ,295 (32 bit) char 2 56 character values float 1.2e– 38 to 3.4e 38 double. procedure for writing a C++ program using Visual C++ is simple and easy. Follow these steps: 1. From the main menu, select Visual C++. 2. Select File | New from the Visual C++ toolbar. Make sure. types supported by C++. 029 31240-9 App A 4/27/00 1: 06 PM Page 547 TABLE A.1. VARIABLE DATA TYPES. Variable Data Type Values unsigned short int 0 to 65 ,535 short int –32, 7 68 to 32, 767 unsigned long

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