C++ Quick Reference C++ Data Ty pe s D ata Ty pe char unsigned char int short int short unsigned short int unsigned sho...
224 downloads
1770 Views
5MB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
C++ Quick Reference C++ Data Ty pe s D ata Ty pe char unsigned char int short int short unsigned short int unsigned short unsigned int unsigned long int long unsigned long int unsigned long float double long double
Descri p t i o n Character Unsigned Character Integer Short integer Same as short int Unsigned short integer Same as unsigned short int Unsigned integer Same as unsigned int Long integer Same as long int Unsigned long integer Same as unsigned long int Single precision floating point double precision floating point Long double precision floating point
Co mmo n l y U sed Operat or s A ss i g n me n t Operator s = += -= *= /= %=
Assignment Combined addition/assignment Combined subtraction/assignment Combined multiplication/assignment Combined division/assignment Combined modulus/assignment
A r i t h me t ic Operat or s + * / %
Addition Subtraction Multiplication Division Modulus (remainder)
R e la t i o na l Operator s < >= == !=
Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to
L o g ical Operat or s && || !
AND OR NOT
I ncremen t / Decre men t
For ms of t he if S tate men t Si mp le i f if (expression) statement;
Exa m p le if (x < y) x++;
i f /e l se if (expression) statement; else statement;
Exa m p le if (x < y) x++; else x--;
i f /e l se if if (expression) statement; else if (expression) statement; else statement;
Exa m p le if (x < y) x++; else if (x < z) x--; else y++;
T o con d i t i o na l l y-- execute more t han one s ta te me n t, encl o se t he sta te men t s i n braces: For m E xa m p le if (expression) if (x < y) { { statement; x++; statement; cout hours; // Get the hourly pay rate. cout > rate; // Calculate the pay. pay = hours * rate; // Display the pay. cout rate;
Once information is gathered from the outside world, a program usually processes it in some manner. In Program 1-1, the hours worked and hourly pay rate are multiplied in line 18 and the result is assigned to the pay variable: pay = hours * rate;
Output is information that a program sends to the outside world. It can be words or graphics displayed on a screen, a report sent to the printer, data stored in a file, or information sent to any device connected to the computer. Lines 10, 14, and 21 in Program 1-1 all perform output: cout operators appear to point in the direction that data is flowing. In a statement that uses the cout object, the > operator always points toward the variable that is receiving the value. This indicates that data is flowing from cin to a variable. This is illustrated in Figure 3-1. Figure 3-1
cout > length; Think of the > operators as arrows that point in the direction that data is flowing.
cout cin
"What is the length of the rectangle? "; length;
The cin object causes a program to wait until data is typed at the keyboard and the [Enter] key is pressed. No other lines in the program will be executed until cin gets its input. cin automatically converts the data read from the keyboard to the data type of the variable used to store it. If the user types 10, it is read as the characters ‘1’ and ‘0’. cin is smart enough to know this will have to be converted to an int value before it is stored in the length variable. cin is also smart enough to know a value like 10.7 cannot be stored in an integer variable. If the user enters a floating-point value for an integer variable, cin will not read the part of the number after the decimal point.
N O T E : You must include the iostream file in any program that uses cin.
Entering Multiple Values The cin object may be used to gather multiple values at once. Look at Program 3-2, which is a modified version of Program 3-1. Line 15 waits for the user to enter two values. The first is assigned to length and the second to width. cin >> length >> width;
81
82
Chapter 3
Expressions and Interactivity
Program 3-2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// This program asks the user to enter the length and width of // a rectangle. It calculates the rectangle's area and displays // the value on the screen. #include using namespace std; int main() { int length, width, area; cout width; area = length * width; cout fractional >> letter; cout sold; store2 -= sold; // Adjust store 2's inventory. // Get the number of widgets sold at store 3. cout > sold; store3 -= sold; // Adjust store 3's inventory. // Display each store's current inventory. cout width; cout > height; (program continues)
135
136
Chapter 3
Program 3-28 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
Expressions and Interactivity
(continued)
// Calculate the crate's volume, the cost to produce it, // the charge to the customer, and the profit. volume = length * width * height; cost = volume * 0.23; charge = volume * 0.5; profit = charge - cost; // Display the calculated data. cout 95) cout 40); cout = 35000 || years > 5)) { cout 2. It is asking “is x not greater than 2?” The second expression, however, applies the ! operator to x only. It is asking “is the logical negation of x greater than 2?” Suppose x is set to 5. Since 5 is nonzero, it would be considered true, so the ! operator would reverse it to false, which is 0. The > operator would then determine if 0 is greater than 2. To avoid a catastrophe like this, always use parentheses! The && and || operators rank lower in precedence than the relational operators, so precedence problems are less likely to occur. If you feel unsure, however, it doesn’t hurt to use parentheses anyway. (a > b) && (x < y) (x == y) || (b > a)
is the same as is the same as
a > b && x < y x == y || b > a
The logical operators have left-to-right associativity. In the following expression, a < b is evaluated before y == z. a < b || y == z
201
202
Chapter 4
Making Decisions
In the following expression, y == z is evaluated first, however, because the && operator has higher precedence than ||. a < b || y == z && m > j
The expression is equivalent to (a < b) || ((y == z) && (m > j))
4.10
Checking Numeric Ranges with Logical Operators C O NC E P T: Logical operators are effective for determining whether a number is in or out of a range. When determining whether a number is inside a numeric range, it’s best to use the && operator. For example, the following if statement checks the value in x to determine whether it is in the range of 20 through 40: if (x >= 20 && x > choice; switch (choice) { case 'A': cout power; bigNum = num; while (count++ < power); bigNum *= num; cout using namespace std; int main () { string town; cout > town; cout manager.birthDate.day; cout > manager.birthDate.year; cin.ignore(); // Skip the remaining newline character // Get the manager's residence information cout , and . operators, and describes what each references. Table 11-3 Expression Description s->m s is a structure pointer and m is a member. This expression accesses the m member of the structure pointed to by s. *a.p a is a structure variable and p, a pointer, is a member. This expression dereferences the value pointed to by p. (*s).m
s is a structure pointer and m is a member. The * operator dereferences s, causing the expression to access the m member of the structure pointed to by s. This expression is the same as s->m .
*s->p
s is a structure pointer and p, a pointer, is a member of the structure pointed to by s. This expression accesses the value pointed to by p. (The -> operator dereferences s and the * operator dereferences p.)
*(*s).p
s is a structure pointer and p, a pointer, is a member of the structure pointed to by s. This expression accesses the value pointed to by p. (*s) dereferences s and the outermost * operator dereferences p. The expression *s->p is equivalent.
Checkpoint Assume the following structure declaration exists for questions 11.11–11.15: struct Rectangle { int length; int width; };
11.11
Write a function that accepts a Rectangle structure as its argument and displays the structure’s contents on the screen.
11.12
Write a function that uses a Rectangle structure reference variable as its parameter and stores the user’s input in the structure’s members.
11.13
Write a function that returns a Rectangle structure. The function should store the user’s input in the members of the structure before returning it.
11.14
Write the definition of a pointer to a Rectangle structure.
11.15
Assume rptr is a pointer to a Rectangle structure. Which of the expressions, A, B, or C, is equivalent to the following expression: rptr->width
A) *rptr.width B) (*rptr).width C) rptr.(*width)
11.11 Unions
11.11
Unions C O NC E P T: A union is like a structure, except all the members occupy the same memory area. A union, in almost all regards, is just like a structure. The difference is that all the members of a union use the same memory area, so only one member can be used at a time. A union might be used in an application where the program needs to work with two or more values (of different data types), but only needs to use one of the values at a time. Unions conserve memory by storing all their members in the same memory location. Unions are declared just like structures, except the key word union is used instead of struct. Here is an example: union PaySource { short hours; float sales; };
A union variable of the data type shown above can then be defined as PaySource employee1;
The PaySource union variable defined here has two members: hours (a short), and sales (a float). The entire variable will only take up as much memory as the largest member (in this case, a float). The way this variable is stored on a typical PC is illustrated in Figure 11-5. Figure 11-5 employee1: a PaySource union variable
First two bytes are used by hours, a short All four bytes are used by sales, a float
As shown in Figure 11-5, the union uses four bytes on a typical PC. It can store a short or a float, depending on which member is used. When a value is stored in the sales member, all four bytes are needed to hold the data. When a value is stored in the hours member, however, only the first two bytes are used. Obviously, both members can’t hold values at the same time. This union is demonstrated in Program 11-10.
621
622
Chapter 11
Structured Data
Program 11-10 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 49 50 51
// This program demonstrates a union. #include #include using namespace std; union PaySource { int hours; float sales; };
// Hours worked // Amount of sales
int main() { PaySource employee1; char payType; float payRate; float grossPay;
// // // //
Define a union variable To hold the pay type Hourly pay rate Gross pay
cout setWidth(10.0); rectPtr->setLength(15.0); // Delete the object from memory. delete rectPtr; rectPtr = 0;
Line 2 defines rectPtr as a Rectangle pointer. Line 5 uses the new operator to dynamically allocate a Rectangle object and assign its address to rectPtr. Lines 8 and 9 store values in the dynamically allocated object’s width and length variables. Figure 13-12 shows the state of the dynamically allocated object after these statements have executed. Figure 13-12 The rectPtr pointer variable holds the address of a dynamically allocated Rectangle object
A Rectangle object width: 10.0
address
length: 15.0
Line 12 deletes the object from memory and line 13 stores the address 0 in rectPtr. Recall from Chapter 9 that this prevents code from inadvertently using the pointer to access the area of memory that has been freed. It also prevents errors from occurring if delete is accidentally called on the pointer again. Program 13-3 is a modification of Program 13-2. In this program, kitchen, bedroom, and den are Rectangle pointers. They are used to dynamically allocate Rectangle objects. The output is the same as Program 13-2.
725
726
Chapter 13
Introduction to Classes
Program 13-3 1 2 3 4 5
// This program creates three instances of the Rectangle class. #include using namespace std; // Rectangle class declaration.
Lines 6 through 62 have been left out. 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
//***************************************************** // Function main * //***************************************************** int main() { double number; double totalArea; Rectangle *kitchen; Rectangle *bedroom; Rectangle *den;
// // // // //
To hold a number The total area To point to kitchen dimensions To point to bedroom dimensions To point to den dimensions
// Dynamically allocate the objects. kitchen = new Rectangle; bedroom = new Rectangle; den = new Rectangle; // Get the kitchen dimensions. cout > number; kitchen->setLength(number); cout > number; kitchen->setWidth(number); // Get the bedroom dimensions. cout > number; bedroom->setLength(number); cout > number; bedroom->setWidth(number); // Get the den dimensions. cout > number; den->setLength(number); cout > number; den->setWidth(number);
// Get the length // Store in kitchen object // Get the width // Store in kitchen object
// Get the length // Store in bedroom object // Get the width // Store in bedroom object
// Get the length // Store in den object // Get the width // Store in den object
// Calculate the total area of the three rooms. totalArea = kitchen->getArea() + bedroom->getArea() + den->getArea();
13.3 Defining an Instance of a Class
109 110 111 112 113 114 115 116 117 118 119 120 121 122 }
// Display the total area of the three rooms. cout rectLength; (program continues)
733
734
Chapter 13
Program 13-4 22 23 24 25 26 27 28 29 30 31 32 33
Introduction to Classes
(continued)
// Store the width and length of the rectangle // in the box object. box.setWidth(rectWidth); box.setLength(rectLength); // Display the rectangle's data. cout > "What is your weight? "; cin mainOfficeRequest; Budget::mainOffice(mainOfficeRequest); Budget divisions[NUM_DIVISIONS]; // Array of Budget objects AuxiliaryOffice auxOffices[4]; // Array of AuxiliaryOffice // Get the budget requests for each division // and their auxiliary offices. for (count = 0; count < NUM_DIVISIONS; count++) { double budgetAmount; // To hold input // Get the request for the division office. cout ), 160–162 greater-than or equal-to operator (>=), 160–162
H hand-tracing, 131–132 hard disk, 5 hardware, 2–5 CPU, 2–4 input devices, 2, 5 main memory, 2, 4 output devices, 2, 5 secondary storage, 2, 4–5 “has-a” relationship, 851 header file, 28 cmath, 92, 129 cstdlib, 131, 357, 559 cstring, 210, 551 ctime, 131 fstream, 137–138 iostream, 28, 36–37 prestandard style, 69 string, 570 hexadecimal literals, 46 hierarchies, class, 897–903 hierarchy chart, 19 high-level languages, 8 Home Software Company case study, 580–581, 764–771
955
956
Index
I IDE, 11 identifiers, 41–42 capitalization, 42 legal, 42 if/else statement, 177–179 if/else if statement, 187–191 trailing else, 188, 190–191 if statement, 164–175 conditionally-executed code, 165–166, 173–175 expanding, 173–175 floating point comparisons, 169–170 indentation, 169 nested, 180–187 programming style, 169 #ifndef directive, 730–731 ifstream objects, 138, 652, 656 >> used with, 141 close member function, 139–140 fail member function, 227 open member function, 138–139 ignore member function, cin, 125–126 implementation file, class, 730 implicit sizing, arrays, 388 #include directive, 28, 36–37, 733 include file directory, 733 include guard, 730–731 increment operator (++), 241–246 mathematical expressions, in, 245 postfix mode, 242–245 prefix mode, 242–245 relational expressions, in, 245–246 indentation, 67–68, 169, 251 indirection operator, 497 infinite loop, 250 inheritance, 871–880 base class, 872 class hierarchies, 897–903 constructors and destructors, 886–891 derived class, 872 “is-a” relationship, 872 multiple, 925–930 redefining functions, 893–897 initialization, 58 arrays, 385–390, 415 arrays of objects, 761 list, 385 partial, array, 387–389 pointers, 506 structure, 599–602 structure array, 606 variable, 58 initialization expression (for loop), 262–263, 267, 268–269
inline expansion, 737 member functions, 735–737 input, 16–17 with cin, 79–85 devices, 5 formatted, 121–126 validation, 193, 203–204, 253–255 input-output stream library, 36 insert member function, string class, 579 instance, 593 class, 717 variables, 801–802 instantiation, 717 int, 43–44 integer data types, 42–43 division, 60, 99–100 IntegerList class, 771–775 integrated development environment (IDE), 11 ios::app access flag, 653 ios::ate access flag, 653 ios::badbit status flag, 663 ios::binary access flag, 653, 675 ios::eofbit status flag, 663 ios::failbit status flag, 663 ios::goodbit status flag, 663 ios::hardfail status flag, 663 ios::in access flag, 653 ios::out access flag, 653 iostream header file, 28, 36–37 ios::trunc access flag, 653 “is-a” relationship, 872, 914–915 isalnum library function, 542 isalpha library function, 542 isdigit library function, 542 islower library function, 542 isprint library function, 542 ispunct library function, 542 isspace library function, 542 isupper library function, 542 iteration, loop, 248 itoa library function, 559–561
J Java, 9 JavaScript, 9
K key words, 13–14, 41–42 keyboard buffer, 85 input with cin, 80–86
L language elements, 12–16 left manipulator, 119–120
length member function, string class, 576–577, 579 less-than operator (> and