c++

Page 194

178

5. Classes

As another example, we now de ne a class for de nite integrals that contains two data members for the lower and upper integral bounds, another data member as a pointer to a function for the integrand, and a few function members and a friend for manipulating and evaluating the definite integral such as the Trapezoidal Rule and Simpson's Rule. Numeric integration was discussed in x3.13 in the procedural programming style as in C and FORTRAN 90. Now class can be used to achieve encapsulation of data and functions and information hiding. It can be declared as typedef double (*pfn)(double)

// define a function pointer

class integral { // members by default are private double lower // lower integral bound double upper // upper integral bound pfn integrand // integrand function public: // public members integral(double a, double b, pfn f){ // a constructor lower = a upper = b integrand = f } double lowbd() const { return lower } // const fcn member double upbd() const { return upper } // const fcn member void changebd(double, double) // nonconst member double trapezoidal(int) const // const fcn member friend double simpson(integral, int) // a friend } // note semicolon

The members lower upper, and integrand are private and can be accessed only by its function members such as integral :: lowbd() and friends such as simpson(): Thus public functions integral :: lowbd() and integral :: upbd() are provided to return the lower and upper integral bounds. When a class has a constructor, all objects of the class must be constructed by calling a constructor. For example, the declaration integral di(0, 5.5, sqrt)

declares di to be of type integral and creates an object with initialization lower = 0:0 upper = 5:5 and integrand = sqrt where sqrt() is the squareroot function in <math:h>: A destructor is not needed for the class since the user does not explicitly allocate space for it using the operator new: De nitions of other function members and the friend can be: inline void integral::changebd(double a, double b) { lower = a // change integral bounds to a, b upper = b } double integral::trapezoidal(int n) const {

// const member


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.