Cientific Omputing Lasses: Dr. Johnson
Cientific Omputing Lasses: Dr. Johnson
Classes
Operator Overloading
S CIENTIFIC C OMPUTING
C LASSES
Dr. Johnson
School of Mathematics
Semester 1 2012
Topics:
Initial value problems for ODEs
Euler’s Method for ODEs
Stability
Aims - week 3:
Be able to solve an initial value ODE problem
Understand where truncation errors come from
Be aware of the concept of stability in a numerical method
Convert mathematical algorithms into code
Topics:
Objects, data and functions together;
Constructors and desctructors;
Access qualifiers;
Operator overloading.
Aims - week 4:
Understand concept of data and functions as members of
an object;
Create and use simple objects (Points, Intergrand function);
Overload operators to enable easy code writing.
D ECLARING A C LASS
The C++ class is used to define an object.
An object is collection of data, along with functions that act
on that data.
The data and functions may have restricted access.
We declare classes in the following way:
class class_name {
private data and functions
access specifier:
data and functions
.
.
.
access specifier:
data and functions
}object list;
E XAMPLE : P OINT
E XAMPLE : P OINT
U SING CLASSES
U SING CLASSES
P OINTING TO AN O BJECT
We can create a pointer to an object in the same way as
standard data types.
OVERLOADING A FUNCTION
OVERLOADING AN OPERATOR
For some of your classes, addition, multiplication etc may
mean something.
For instance, we may want to be able to write:
Point a(2,1),b(3,4),c;
c = a + b;
OVERLOADING AN OPERATOR
For some of your classes, addition, multiplication etc may
mean something.
For instance, we may want to be able to write:
Point a(2,1),b(3,4),c;
c = a + b;
C++ allows us to overload operators.
So for the above to work we must include the function:
Point operator+(const Point& a,const Point&
b){
Point temp;
temp.set_x(a.get_x() + b.get_x());
temp.set_y(a.get_y() + b.get_y());
return (temp); }
Dr. Johnson MATH49111
Review
Classes
Operator Overloading
class Intergrand{
public:
double operator()(double x) const {
return 1 + x*x;}
};
G ENERIC ROUTINES
We saw that there were problems if the arguments to a
function need to be changed
Good codes will provide generic interfaces.
For example, the trapezium rule may be written:
double trapezium(double a,double b,
int n,const Integrand& f){
double h=(b-a)/n;
double sum=f(a)/2.;
for(int i=1;i<n;i++){
x=a+i*h;
sum = sum + f(x);}
sum = sum + f(b)/2.;
return sum*h;
}
Dr. Johnson MATH49111
Review
Classes
Operator Overloading
S UMMARY
Topics:
Objects, data and functions together;
Constructors and desctructors;
Access qualifiers;
Operator overloading.
Aims - week 4:
Understand concept of data and functions as members of
an object;
Create and use simple objects (Points, Intergrand function);
Overload operators to enable easy code writing.