A Complete Guide to Programming in C++ part 27 pdf

10 374 0
A Complete Guide to Programming in C++ part 27 pdf

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

Thông tin tài liệu

SOLUTIONS ■ 239 // Function circle(): Compute circumference and area. void circle( const double& r, double& u, double& f) { const double pi = 3.1415926536; u = 2 * pi * r; f = pi * r * r; } Exercise 3 // // swap.cpp // Definition and call of the function swap(). // 1. version: parameters with pointer type, // 2. version: parameters with reference type. // #include <iostream> using namespace std; void swap( float*, float*); // Prototypes of swap() void swap( float&, float&); int main() { float x = 11.1F; float y = 22.2F; cout << "x and y before swapping: " << x << " " << y << endl; swap( &x, &y); // Call pointer version. cout << "x and y after 1. swapping: " << x << " " << y << endl; swap( x, y); // Call reference version. cout << "x and y after 2. swapping: " << x << " " << y << endl; return 0; } void swap(float *p1, float *p2) // Pointer version { float temp; // Temporary variable temp = *p1; // Above call points p1 *p1 = *p2; // to x and p2 to y. *p2 = temp; } 240 ■ CHAPTER 12 REFERENCES AND POINTERS void swap(float& a, float& b) // Reference version { float temp; // Temporary variable temp = a; // For above call a = b; // a equals x and b equals y b = temp; } Exercise 4 // // quadEqu.cpp // Defines and calls the function quadEquation(), // which computes the solutions of quadratic equations // a*x*x + b*x + c = 0 // The equation and its solutions are printed by // the function printQuadEquation(). // #include <iostream> #include <iomanip> #include <string> #include <cmath> // For the square root sqrt() using namespace std; string header = " *** Solutions of Quadratic Equations ***\n", line( 50, '-'); // Prototypes // Computing solutions: bool quadEquation( double a, double b, double c, double* x1Ptr, double* x2Ptr); // Printing the equation and its solutions: void printQuadEquation( double a, double b, double c); int main() { cout << header << endl; printQuadEquation( 2.0, -2.0, -1.5); printQuadEquation( 1.0, -6.0, 9.0); printQuadEquation( 2.0, 0.0, 2.0); return 0; } SOLUTIONS ■ 241 // Prints the equation and its solutions: void printQuadEquation( double a, double b, double c) { double x1 = 0.0, x2 = 0.0; // For solutions cout << line << '\n' << "\nThe quadratic equation:\n\t " << a << "*x*x + " << b << "*x + " << c << " = 0" << endl; if( quadEquation( a, b, c, &x1, &x2) ) { cout << "has real solutions:" << "\n\t x1 = " << x1 << "\n\t x2 = " << x2 << endl; } else cout << "has no real solutions!" << endl; cout << "\nGo on with return. \n\n"; cin.get(); } bool quadEquation( double a, double b, double c, double* x1Ptr, double* x2Ptr) // Computes the solutions of the quadratic equation: // a*x*x + b*x + c = 0 // Stores the solutions in the variables to which // x1Ptr and x2Ptr point. // Returns: true, if a solution exists, // otherwise false. { bool return_flag = false; double help = b*b - 4*a*c; if( help >= 0) // There are real solutions. { help = sqrt( help); *x1Ptr = (-b + help) / (2*a); *x2Ptr = (-b - help) / (2*a); return_flag = true; } return return_flag; } This page intentionally left blank 243 Defining Classes This chapter describes how classes are defined and how instances of classes, that is, objects, are used. In addition, structs and unions are introduced as examples of special classes. chapter 13 244 ■ CHAPTER 13 DEFINING CLASSES Real World A Car Abstraction Instantiation Class CAR Objects Properties (Data Members): Date when built Capacity (PS) Serial number . . . Properties: Date when built = 1990 Capacity = 100 Chassis number = 11111 . . . Methods . . . Methods (Member functions): to run, to brake, to park, to turn off . . . car1 Properties: Date when built = 2000 Capacity = 200 Chassis number = 22222 . . . Methods . . . car2 • • • ■ THE CLASS CONCEPT THE CLASS CONCEPT ■ 245 Classes are the language element in C++ most important to the support object-oriented programming (OOP). A class defines the properties and capacities of an object. ᮀ Data Abstraction Humans use abstraction in order to manage complex situations. Objects and processes are reduced to basics and referred to in generic terms. Classes allow more direct use of the results of this type of abstraction in software development. The first step towards solving a problem is analysis. In object-oriented programming, analysis comprises identifying and describing objects and recognizing their mutual rela- tionships. Object descriptions are the building blocks of classes. In C++, a class is a user-defined type. It contains data members, which describe the properties of the class, and member functions, or methods, which describe the capacities of the objects. Classes are simply patterns used to instantiate, or create, objects of the class type. In other words, an object is a variable of a given class. ᮀ Data Encapsulation When you define a class, you also specify the private members, that is, the members that are not available for external access, and the public members of that class. An applica- tion program accesses objects by using the public methods of the class and thus activat- ing its capacities. Access to object data is rarely direct, that is, object data is normally declared as pri- vate and then read or modified by methods with public declarations to ensure correct access to the data. One important aspect of this technique is the fact that application programs need not be aware of the internal structure of the data. If needed, the internal structure of the pro- gram data can even be modified. Provided that the interfaces of the public methods remain unchanged, changes like these will not affect the application program. This allows you to enhance an application by programming an improved class version without changing a single byte of the application. An object is thus seen to encapsulate its private structure, protecting itself from exter- nal influences and managing itself by its own methods. This describes the concept of data encapsulation concisely. 246 ■ CHAPTER 13 DEFINING CLASSES class Demo { private: // Private data members and methods here public: // Public data members and methods here }; // account.h // Defining the class Account. // #ifndef _ACCOUNT_ // Avoid multiple inclusions. #define _ACCOUNT_ #include <iostream> #include <string> using namespace std; class Account { private: // Sheltered members: string name; // Account holder unsigned long nr; // Account number double balance; // Account balance public: //Public interface: bool init( const string&, unsigned long, double); void display(); }; #endif // _ACCOUNT_ ■ DEFINING CLASSES Definition scheme Example of a class DEFINING CLASSES ■ 247 A class definition specifies the name of the class and the names and types of the class members. The definition begins with the keyword class followed by the class name. The data members and methods are then declared in the subsequent code block. Data members and member functions can belong to any valid type, even to another previously defined class. At the same time, the class members are divided into: ■ private members, which cannot be accessed externally ■ public members, which are available for external access. The public members form the so-called public interface of the class. The opposite page shows a schematic definition of a class. The private section gen- erally contains data members and the public section contains the access methods for the data. This provides for data encapsulation. The following example includes a class named Account used to represent a bank account. The data members, such as the name of the account holder, the account num- ber, and the account balance, are declared as private. In addition, there are two public methods, init() for initialization purposes and display(), which is used to display the data on screen. The labels private: and public: can be used at the programmer’s discretion within a class: ■ you can use the labels as often as needed, or not at all, and in any order. A sec- tion marked as private: or public: is valid until the next public: or pri- vate: label occurs ■ the default value for member access is private. If you omit both the private and public labels, all the class members are assumed to be private. ᮀ Naming Every piece of software uses a set of naming rules. These rules often reflect the target platform and the class libraries used. For the purposes of this book, we decided to keep to standard naming conventions for distinguishing classes and class members. Class names begin with an uppercase letter and member names with a lowercase letter. Members of different classes can share the same name. A member of another class could therefore also be named display(). 248 ■ CHAPTER 13 DEFINING CLASSES // account.cpp // Defines methods init() and display(). // #include "account.h" // Class definition #include <iostream> #include <iomanip> using namespace std; // The method init() copies the given arguments // into the private members of the class. bool Account::init(const string& i_name, unsigned long i_nr, double i_balance) { if( i_name.size() < 1) // No empty name return false; name = i_name; nr = i_nr; balance = i_balance; return true; } // The method display() outputs private data. void Account::display() { cout << fixed << setprecision(2) << " \n" << "Account holder: " << name << '\n' << "Account number: " << nr << '\n' << "Account balance: " << balance << '\n' << " \n" << endl; } ■ DEFINING METHODS Methods of class Account . unions are introduced as examples of special classes. chapter 13 244 ■ CHAPTER 13 DEFINING CLASSES Real World A Car Abstraction Instantiation Class CAR Objects Properties (Data Members): Date when. in C++ most important to the support object-oriented programming (OOP). A class defines the properties and capacities of an object. ᮀ Data Abstraction Humans use abstraction in order to manage. the capacities of the objects. Classes are simply patterns used to instantiate, or create, objects of the class type. In other words, an object is a variable of a given class. ᮀ Data Encapsulation When

Ngày đăng: 06/07/2014, 17:21

Từ khóa liên quan

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

Tài liệu liên quan