oop Lecture 6

867 views

Published on

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
867
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

oop Lecture 6

  1. 1. OOP Lecture 4, 3rd March, 2011 M. Anwar-ul-HaqQuestion: Create a class called Complex for performing arithmetic with complexnumbers. Write a driver program to test your class. Complex numbers have the form realPart + imaginaryPart * iUse double variables to represent the private data of the class. Provide a constructorfunction that enables an object of this class to be initialized when it is declared. Theconstructor should contain default values in case no initializers are provided. Providepublic member functions for each of the following:a) Addition of two Complex numbers: The real parts are added together and theimaginary parts are added together.b) Subtraction of two Complex numbers: The real part of the right operand is subtractedfrom the real part of the left operand and the imaginary part of the right operand issubtracted from the imaginary part of the left operand.c) Printing Complex numbers in the form (a, b) where a is the real part and b is theimaginary part. OOP, Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Islamabad
  2. 2. Solution:#include <iostream>using namespace std;class Complex {public: Complex( double = 0.0, double = 0.0 ); // default constructor void addition( const Complex & ); void subtraction( const Complex & ); void printComplex( void ); void setComplexNumber( double, double );private: double realPart; double imaginaryPart; };Complex::Complex( double real, double imaginary ){ setComplexNumber( real, imaginary ); }void Complex::addition( const Complex &a ) { realPart += a.realPart; imaginaryPart += a.imaginaryPart; } void Complex::subtraction( const Complex &s ) { realPart -= s.realPart; imaginaryPart -= s.imaginaryPart; } void Complex::printComplex( void ) { cout << ( << realPart << ", " << imaginaryPart << ); } void Complex::setComplexNumber( double rp, double ip ) { realPart = rp; imaginaryPart = ip; } int main(){ Complex b( 1, 7 ), c( 9, 2 ); b.printComplex(); cout << " + "; c.printComplex(); cout << " = "; b.addition( c ); b.printComplex(); cout << n; b.setComplexNumber( 10, 1 ); // reset realPart and imaginaryPart OOP, Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Islamabad
  3. 3. c.setComplexNumber( 11, 5 ); b.printComplex(); cout << " - "; c.printComplex(); cout << " = "; b.subtraction( c ); b.printComplex(); cout << endl; return 0;} OOP, Spring 2011, Engr. Anwar, Foundation University (FUIEMS), Islamabad

×