ADT Specification Example TYPE Complex Number DOMAIN Each
ADT Specification Example TYPE Complex. Number 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 1
Representations of Complex. Number 2 double variables 2 float variables actual choice of representation depends on actual application (possible values of complex number ) 10 45 2
class Complex Specification // SPECIFICATION FILE class Complex // declares a class data type { // does not allocate memory public : // public function members void set. Real ( double r ) ; void set. Img( double im); double get. Real(); double get. Img(); 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 : double }; // private data members real ; img ; 3 3
Use of C++ data Type class l software that uses the class is called a client l variables of the class type are called class objects or class instances l client code uses public member functions to handle its class objects 4
Client Code Using Complex #include “comlex. h” int main ( ) { Complex num 1, num 2; Complex sum; double real, img; } // includes specification of the class cout<<“Enter the real and imaginary parts for the first numern”; cin>>ral >> img; num 1. set. Real(real); num 1. set. Img(img); cout<<“Enter the real and imaginary parts for the second numbern”; cin>>real>>img; num 2. setreal(real); num 2. set. Img(img); sum = num 1. plus(num 2); cout<< “the num 1 + num 2 =“<< sum. print()<, endl; return 0; 5 5
Implementation of plus function l l l l 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 6
Implementation of print function l Void Complex: : print() const l{ l cout<<“ (“<<real <<“, “<<img<<“)”’ l} 7
Implementation of set functions l void Complex: : set. Real(double r) l{ l real = r; l} l // you write the implementation of l // set. Img( double i) 8
Implementation of Compare l bool Complex: : Equal(Complex c) l{ if ( real == c. real && img == c. img) return true; else return false; l l } 9
Specification of Complex Class Constructors class Complex { public : // Complex. h // function members Complex( double real, double img ) ; // constructor Complex ( ) ; private : double real ; double img ; }; // default constructor // 2 data members 10 10
Implementation of Complex Default Constructor Complex : : Complex ( ) { real = 0 ; img = 0 ; } 11 11
Implementation of Another Complex Class Constructor Complex : : Complex ( /* in */ double r, /* in */ double i) { real = r ; img = i ; } 12 12
- Slides: 12