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

Absolute C++ (4th Edition) part 24 pps

10 379 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 227,49 KB

Nội dung

Structures 233 Display 6.2 A Structure with A Structure Member (part 2 of 2) 41 << "-" << account.maturity.year << endl 42 << "it had a balance of $" 43 << account.balanceAtMaturity << endl; 44 return 0; 45 } 46 //uses iostream: 47 void getCDData(CDAccount& theAccount) 48 { 49 cout << "Enter account initial balance: $"; 50 cin >> theAccount.initialBalance; 51 cout << "Enter account interest rate: "; 52 cin >> theAccount.interestRate; 53 cout << "Enter the number of months until maturity: "; 54 cin >> theAccount.term; 55 cout << "Enter the maturity date:\n"; 56 getDate(theAccount.maturity); 57 } 58 //uses iostream: 59 void getDate(Date& theDate) 60 { 61 cout << "Enter month: "; 62 cin >> theDate.month; 63 cout << "Enter day: "; 64 cin >> theDate.day; 65 cout << "Enter year: "; 66 cin >> theDate.year; 67 } S AMPLE D IALOGUE Enter account data on the day account was opened: Enter account initial balance: $100.00 Enter account interest rate: 10.0 Enter the number of months until maturity: 6 Enter the maturity date: Enter month: 2 Enter day: 14 Enter year: 1899 When the CD matured on 2-14-1899 it had a balance of $105.00 06_CH06.fm Page 233 Wednesday, August 13, 2003 12:54 PM 234 Structures and Classes Self-Test Exercises ■ INITIALIZING STRUCTURES You can initialize a structure at the time that it is declared. To give a structure variable a value, follow it by an equal sign and a list of the member values enclosed in braces. For example, the following definition of a structure type for a date was given in the previ- ous subsection: struct Date { int month; int day; int year; }; Once the type Date is defined, you can declare and initialize a structure variable called dueDate as follows: Date dueDate = {12, 31, 2003}; The initializing values must be given in the order that corresponds to the order of mem- ber variables in the structure type definition. In this example, dueDate.month receives the first initializing value of 12, dueDate.day receives the second value of 31, and due- Date.year receives the third value of 2003. It is an error if there are more initializer values than struct members. If there are fewer initializer values than struct members, the provided values are used to initialize data members, in order. Each data member without an initializer is initialized to a zero value of an appropriate type for the variable. 1. Given the following structure and structure variable declaration, struct CDAccountV2 { double balance; double interestRate; int term; char initial1; char initial2; }; CDAccountV2 account; what is the type of each of the following? Mark any that are not correct. a. account.balance b. account.interestRate 06_CH06.fm Page 234 Wednesday, August 13, 2003 12:54 PM Structures 235 c. CDAccountV1.term d. account.initial2 e. account 2. Consider the following type definition: struct ShoeType { char style; double price; }; Given the above structure type definitions, what will be the output produced by the following code? ShoeType shoe1, shoe2; shoe1.style =’A’; shoe1.price = 9.99; cout << shoe1.style << " $" << shoe1.price << endl; shoe2 = shoe1; shoe2.price = shoe2.price/9; cout << shoe2.style << " $" << shoe2.price << endl; 3. What is the error in the following structure definition? struct Stuff { int b; int c; } int main( ) { Stuff x; // other code } 4. Given the following struct definition, struct A { int member b; int member c; }; declare x to have this structure type. Initialize the members of x, member b and member c, to the values 1 and 2, respectively. 06_CH06.fm Page 235 Wednesday, August 13, 2003 12:54 PM 236 Structures and Classes 5. Here is an initialization of a structure type. State what happens with each initialization. Note any problems with these initializations. struct Date { int month; int day; int year; }; a. Date dueDate = {12, 21}; b. Date dueDate = {12, 21, 1995}; c. Date dueDate = {12, 21, 19, 95}; 6. Write a definition for a structure type for records consisting of a person’s wage rate, accrued vacation (which is some whole number of days), and status (which is either hourly or sala- ried). Represent the status as one of the two char values ’H’ and ’S’. Call the type EmployeeRecord. 7. Give a function definition corresponding to the following function declaration. (The type ShoeType is given in Self-Test Exercise 2.) void readShoeRecord(ShoeType& newShoe); //Fills newShoe with values read from the keyboard. 8. Give a function definition corresponding to the following function declaration. (The type ShoeType is given in Self-Test Exercise 2.) ShoeType discount(ShoeType oldRecord); //Returns a structure that is the same as its argument, //but with the price reduced by 10%. Classes We all know—the Times knows—but we pretend we don’t. Virginia Woolf, Monday or Tuesday A class is basically a structure with member functions as well as member data. Classes are central to the programming methodology known as object-oriented programming. ■ DEFINING CLASSES AND MEMBER FUNCTIONS A class is a type that is similar to a structure type, but a class type normally has member functions as well as member variables. An overly simple, but illustrative, example of a class called DayOfYear is given in Display 6.3. This class has one member function 6.2 class 06_CH06.fm Page 236 Wednesday, August 13, 2003 12:54 PM Classes 237 named output, as well as the two member variables month and day. The term public: is called an access specifier. It simply means that there are no restrictions on the members that follow. We will discuss public: and its alternatives after going through this simple example. The type DayOfYear defined in Display 6.3 is a class definition for objects whose values are dates, such as January 1 or July 4. Display 6.3 Class with a Member Function (part 1 of 2) 1 //Program to demonstrate a very simple example of a class. 2 //A better version of the class DayOfYear will be given in Display 6.4. 3 #include <iostream> 4 using namespace std; 5 class DayOfYear 6 { 7 public: 8 void output( ); 9 int month; 10 int day; 11 }; 12 int main( ) 13 { 14 DayOfYear today, birthday; 15 cout << "Enter today’s date:\n"; 16 cout << "Enter month as a number: "; 17 cin >> today.month; 18 cout << "Enter the day of the month: "; 19 cin >> today.day; 20 cout << "Enter your birthday:\n"; 21 cout << "Enter month as a number: "; 22 cin >> birthday.month; 23 cout << "Enter the day of the month: "; 24 cin >> birthday.day; 25 cout << "Today’s date is "; 26 today.output( ); 27 cout << endl; 28 cout << "Your birthday is "; 29 birthday.output( ); 30 cout << endl; 31 if (today.month == birthday.month && today.day == birthday.day) 32 cout << "Happy Birthday!\n"; 33 else 34 cout << "Happy Unbirthday!\n"; 35 return 0; 36 } Member function declaration Normally, member variables are private and not public, as in this example. This is discussed a bit later in this chapter. Calls to the member function output 06_CH06.fm Page 237 Wednesday, August 13, 2003 12:54 PM 238 Structures and Classes Display 6.3 Class with a Member Function (part 2 of 2) 37 //Uses iostream: 38 void DayOfYear::output( ) 39 { 40 switch (month) 41 { 42 case 1: 43 cout << "January "; break; 44 case 2: 45 cout << "February "; break; 46 case 3: 47 cout << "March "; break; 48 case 4: 49 cout << "April "; break; 50 case 5: 51 cout << "May "; break; 52 case 6: 53 cout << "June "; break; 54 case 7: 55 cout << "July "; break; 56 case 8: 57 cout << "August "; break; 58 case 9: 59 cout << "September "; break; 60 case 10: 61 cout << "October "; break; 62 case 11: 63 cout << "November "; break; 64 case 12: 65 cout << "December "; break; 66 default: 67 cout << "Error in DayOfYear::output. Contact software vendor."; 68 } 69 70 cout << day; 71 } S AMPLE D IALOGUE Enter today’s date: Enter month as a number: 10 Enter the day of the month: 15 Enter your birthday: Enter month as a number: 2 Enter the day of the month: 21 Today’s date is October 15 Your birthday is February 21 Happy Unbirthday! Member function definition 06_CH06.fm Page 238 Wednesday, August 13, 2003 12:54 PM Classes 239 The value of a variable of a class type is called an object (therefore, when speaking loosely, a variable of a class type is also often called an object). An object has both data members and function members. When programming with classes, a program is viewed as a collection of interacting objects. The objects can interact because they are capable of actions, namely, invocations of member functions. Variables of a class type hold objects as values. Variables of a class type are declared in the same way as variables of the predefined types and in the same way as structure variables. For the moment ignore the word public: shown in Display 6.3. The rest of the def- inition of the class DayOfYear is very much like a structure definition, except that it uses the keyword class instead of struct and it lists the member function output (as well as the member variables month and day). Notice that the member function output is listed by giving its declaration (prototype). A class definition normally contains only the declaration for its member functions. The definitions for the member functions are usually given elsewhere. In a C++ class definition, you can intermix the ordering of the member variables and member functions in any way you wish, but the style we will fol- low has a tendency to list the member functions before the member variables. Member variables for an object of a class type are specified using the dot operator in the same way that the dot operator is used to specify member variables of a structure. For example, if today is a variable of the class type DayOfYear defined in Display 6.3, then today.month and today.day are the two member variables of the object today. Member functions for classes that you define are invoked using the dot operator in a way that is similar to how you specify a member variable. For example, the program in Display 6.3 declares two objects of type DayOfYear in the following way: DayOfYear today, birthday; The member function output is called with the object today as follows: today.output( ); and the member function output is called with the object birthday as follows: birthday.output( ); When a member function is defined, the definition must include the class name because there may be two or more classes that have member functions with the same name. In Display 6.3 there is only one class definition, but in other situations you may have many class definitions, and more than one class may have member functions with the same name. The definition for the member function output of the class DayOfYear is shown in part 2 of Display 6.3. The definition is similar to an ordinary function defini- tion except that you must specify the class name in the heading of the function definition. The heading of the function definition for the member function output is as follows: void DayOfYear::output( ) The operator :: is called the scope resolution operator and serves a purpose similar to that of the dot operator. Both the dot operator and the scope resolution operator are used object member function calling member functions defining member functions scope resolution operator 06_CH06.fm Page 239 Wednesday, August 13, 2003 12:54 PM 240 Structures and Classes to tell what a member function is a member of. However, the scope resolution operator :: is used with a class name, whereas the dot operator is used with objects (that is, with class variables). The scope resolution operator consists of two colons with no space between them. The class name that precedes the scope resolution operator is often called a type qualifier, because it specializes (“qualifies”) the function name to one particular type. Look at the definition of the member function DayOfYear::output given in Display 6.3. Notice that in the function definition of DayOfYear::output, we used the member names month and day by themselves without first giving the object and dot operator. That is not as strange as it may at first appear. At this point we are simply defining the member function output. This definition of output will apply to all objects of type DayOfYear, but at this point we do not know the names of the objects of type DayOfYear that we will use, so we cannot give their names. When the member function is called, as in today.output( ); all the member names in the function definition are specialized to the name of the call- ing object. So, the above function call is equivalent to the following: { switch (today.month) { case 1: . . . } cout << today.day; } type qualifier member variables in function definitions M EMBER F UNCTION D EFINITION A member function is defined similar to any other function except that the Class_Name and the scope resolution operator, ::, are given in the function heading. S YNTAX Returned_Type Class_Name :: Function_Name ( Parameter_List ) { Function_Body_Statements } E XAMPLE See Display 6.3. Note that the member variables (month and day) are not preceded by an object name and dot when they occur in a member function definition. 06_CH06.fm Page 240 Wednesday, August 13, 2003 12:54 PM Classes 241 Self-Test Exercises In the function definition for a member function, you can use the names of all mem- bers of that class (both the data members and the function members) without using the dot operator. 9. Below we have redefined the class DayOfYear from Display 6.3 so that it now has one additional member function called input. Write an appropriate definition for the member function input. class DayOfYear { public: T HE D OT O PERATOR AND THE S COPE R ESOLUTION O PERATOR Both the dot operator and the scope resolution operator are used with member names to specify of what thing they are a member. For example, suppose you have declared a class called DayOf- Year and you declare an object called today as follows: DayOfYear today; You use the dot operator to specify a member of the object today. For example, output is a member function for the class DayOfYear (defined in Display 6.3), and the following function call will output the data values stored in the object today: today.output( ); You use the scope resolution operator, ::, to specify the class name when giving the function definition for a member function. For example, the heading of the function definition for the member function output would be as follows: void DayOfYear::output( ) Remember, the scope resolution operator, ::, is used with a class name, whereas the dot operator is used with an object of that class. A C LASS I S A F ULL -F LEDGED T YPE A class is a type just like the types int and double. You can have variables of a class type, you can have parameters of a class type, a function can return a value of a class type, and more gen- erally, you can use a class type like any other type. 06_CH06.fm Page 241 Wednesday, August 13, 2003 12:54 PM 242 Structures and Classes void input( ); void output( ); int month; int day; }; 10. Given the following class definition, write an appropriate definition for the member func- tion set. class Temperature { public: void set(double newDegrees, char newScale); //Sets the member variables to the values given as //arguments. double degrees; char scale; //’F’ for Fahrenheit or ’C’ for Celsius. }; 11. Carefully distinguish between the meaning and use of the dot operator and the scope reso- lution operator, ::. ■ ENCAPSULATION A data type, such as the type int, has certain specified values, such as 0, 1, −1, 2, and so forth. You tend to think of the data type as being these values, but the operations on these values are just as important as the values. Without the operations, you could do nothing of interest with the values. The operations for the type int consist of +, −, *, /, %, and a few other operators and predefined library functions. You should not think of a data type as being simply a collection of values. A data type consists of a collection of values together with a set of basic operations defined on these values. A data type is called an abstract data type (abbreviated ADT) if the programmers who use the type do not have access to the details of how the values and operations are implemented. The predefined types, such as int, are abstract data types (ADTs). You do not know how the operations, such as + and *, are implemented for the type int. Even if you did know, you could not use this information in any C++ program. Classes, which are programmer-defined types, should also be ADTs; that is, the details of how the “opera- tions” are implemented should be hidden from, or at least irrelevant to, any program- mer who uses the class. The operations of a class are the (public) member functions of the class. A programmer who uses a class should not need to even look at the defini- tions of the member functions. The member function declarations, given in the class definition, and a few comments should be all the programmer needs in order to use the class. data types and abstract data types 06_CH06.fm Page 242 Wednesday, August 13, 2003 12:54 PM . and dot when they occur in a member function definition. 06_CH06.fm Page 240 Wednesday, August 13, 2003 12:54 PM Classes 241 Self-Test Exercises In the function definition for a member function,. gen- erally, you can use a class type like any other type. 06_CH06.fm Page 241 Wednesday, August 13, 2003 12:54 PM 242 Structures and Classes void input( ); void output( ); int month; int day; . "; 22 cin >> birthday.month; 23 cout << "Enter the day of the month: "; 24 cin >> birthday.day; 25 cout << "Today’s date is "; 26 today.output( ); 27

Ngày đăng: 04/07/2014, 05:21

TỪ KHÓA LIÊN QUAN