Download presentation
1
ADT Specification Example
TYPE ComplexNumber DOMAIN Each complex number can represented by real and imaginary part. OPERATIONS Set the real part set the imaginary part get the real part get the imaginary part plus another complex number minus another complex number multiply another complex number divide another complex number compare with another complex number
2
Representations of ComplexNumber
2 double variables 2 float variables actual choice of representation depends on actual application (possible values of complex number )
3
class Complex Specification
// SPECIFICATION FILE class Complex // declares a class data type { // does not allocate memory public : // public function members void setReal ( double r ) ; void setImg( double im); double getReal(); double getImg(); Complex plus( Complex c); Complex minus(Complex c); Complex multiply(Complex c); Complex divide( Complex c); void print() const ; bool Equal ( Complex c) const ; private : // private data members double real ; double img ; } ; 3
4
Use of C++ data Type class
software that uses the class is called a client variables of the class type are called class objects or class instances client code uses public member functions to handle its class objects
5
Client Code Using Complex
#include “comlex.h” // includes specification of the class int main ( ) { Complex num1, num2; Complex sum; double real, img; cout<<“Enter the real and imaginary parts for the first numer\n”; cin>>ral >> img; num1.setReal(real); num1.setImg(img); cout<<“Enter the real and imaginary parts for the second number\n”; cin>>real>>img; num2.setreal(real); num2.setImg(img); sum = num1.plus(num2); cout<< “the num1 + num2 =“<< sum.print()<,endl; return 0; } 5
6
Implementation of plus function
Complex Complex::plus(Complex c) { Complex sum; sum.real = real + c.real; sum.img = img + c.img; return sum; } // you complete implementations for minus, multiply and divide
7
Implementation of print function
Void Complex::print() const { cout<<“ (“<<real <<“, “<<img<<“)”’ }
8
Implementation of set functions
void Complex::setReal(double r) { real = r; } // you write the implementation of // setImg( double i)
9
Implementation of Compare
bool Complex::Equal(Complex c) { if ( real == c.real && img == c.img) return true; else return false; }
10
Specification of Complex Class Constructors
class Complex // Complex.h { public : // function members Complex( double real, double img ) ; // constructor Complex ( ) ; // default constructor private : // 2 data members double real ; double img ; } ; 10
11
Implementation of Complex Default Constructor
Complex :: Complex ( ) { real = 0 ; img = 0 ; } 11
12
Implementation of Another Complex Class Constructor
Complex :: Complex ( /* in */ double r, /* in */ double i) { real = r ; img = i ; } 12
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.