Question

In: Computer Science

Lab Assignment Objectives 'Be able to overload combined binary operators as member operator functions. Show how...

Lab Assignment Objectives

  1. 'Be able to overload combined binary operators as member operator functions.
  2. Show how to overload binary operators as friend functions.
  3. Show how to convert from a fundamental type to a user-defined type using a constructor.
  4. Understand exception handling mechanisms using try-catch block statements.

Understand the Application

Complex Numbers

A complex number, c, is an ordered pair of real numbers (doubles). For example, for any two real numbers, s and t, we can form the complex number:

This is only part of what makes a complex number complex. Another important aspect is the definition of special rules for adding, multiplying, dividing, etc. these ordered pairs. Complex numbers are more than simply x-y coordinates because of these operations. Examples of complex numbers in this format are (3, 3), (-1, -5), (1.034, 77.5) and (99.9, -108.5). You will build a class of complex numbers called Complex.

One important property of every complex number, c, is its length, or modulus, defined as follows. If c = (s, t) then:

For example:

The Program Specification

Create a class of Complex numbers.

Private Data

  • double real, double imag - These two doubles define the Complex number and are called the real and imaginary parts. Think of each Complex number as an ordered pair, (real, imag) of doubles.

Public Instance Methods

  • Constructors - Allow Complex objects to be constructed with zero, one or two double arguments. The zero-parameter constructor initializes the complex number to (0, 0). The one-parameter constructor should set the real member to the argument passed and set the imag member to 0. The two-parameter constructor should set both real and imag according to the parameters.  DO ALL THREE VERSIONS IN A SINGLE CONSTRUCTOR USING DEFAULT PARAMETERS.
  • Accessors/Mutators - The usual -- two mutators, two accessors.
  • double modulus() - This will return the double |c|, i.e., the modulus, of the complex number. If the Complex object, c, represents the ordered pair (s, t), then the formula above will give the double value to return.
  • Complex reciprocal() - This is defined in the division operator definition, below.
  • toString() - This will return a string like "(-23.4, 8.9)" to the client.  Do not provide a show() or display() method. You will do this using your insertion operator as shown below.
  • Operators - I will describe several operators that you must implement for the class. Some will be defined externally (which I will call friend operators. However, you may, or may not really need to declare them to be friends - all you need to know is that if I say "friend" I mean implement the operator as a non-member. Otherwise, implement it as a member.
  • Exception Class -

    Division By Zero

    Create your own DivByZeroException as a nested class.

    Make sure that both your reciprocal() and operator/() functions throw this exception (you can do this by only throwing it for reciprocal() if you do it correctly). Test it out in your client with a try/catch block, attempting both a normal, and a fatal division.

    To test for division by zero, look at the reciprocal() and test for that being zero. However, not to test for == 0.0 exactly, because of inaccuracies in computer storage of doubles. Instead, pick a literal like .00000001 and proclaim the a complex object to be zero if its modulus (or modulus squared) is less than that literal value.

Description of the Operators

Operators +, -, * and /

Provide four overloaded operators, +, -, * and /. Implement these operators as friend methods of the class, so that  Complex objects can be combined using these four operations. Also, allow a mixed mode operation containing a double and a Complex (which would return a Complex), by treating a double x, as if it were the complex number (x,0). This should come about naturally as a result of the Complex/Complex operators and the proper constructor definitions, not by creating 3 overloads for each operator.

The rules for adding complex numbers are:

   (r,i) + (s,j) = (r + s, i + j).

Subtraction is defined analogously. Multiplication is defined by the rule:

   (r,i) * (s,j) = (r*s - i*j, r*j + s*i).

To define division, first define the operation reciprocal of the complex number c = (r,i) as follows.  c.reciprocal() should return the complex number = ( r / (r*r + i*i),   -i / (r*r + i*i) ), if (r*r + i*i) is not zero. If (r*r + i*i) is zero, then reciprocal() throws an exception.

Then define division with the help of the reciprocal() function (informally):

   (r,i) / (s,j) = (r,i) * reciprocal(s,j)

Notice that if you correspond a normal double number x, with its complex counterpart, (x,0), then you can think of the ordinary double numbers as a subset of the complex numbers. Also, note that, under this correspondence, these four operations result in ordinary addition, multiplication, etc. for the double subset. Try adding or dividing (6,0) and(3,0) for an example.

Testing Specification

In summary, you should be able to handle the combinations below:

   Complex a(3,-4), b(1.1, 2.1), c;
   double x=2, y= -1.7;

   c = a + b;
   c = x - a;
   c = b * y;

   // and also:
   c = 8 + a;
   c = b / 3.2;

To help you confirm your computations, here are some examples:

(1, 2)  + (3, 4)  = (4, 6) 
(1, 2)  - (3, 4)  = (-2, -2) 
(1, 2)  * (3, 4)  = (-5, 10) 
(1, 2)  / (3, 4)  = (0.44, 0.08) 
(1, 2)  + 10 = (11, 2) 
10 / (3, 4)  = (1.2, -1.6) 

Operators << and =

Overload the insertion and assignment operators in the expected ways.

Operators < and ==

a < b should mean |a| < |b|, that is,  a.modulus() < b.modulus().  a == b should mean (a.real == b.real) && (a.imag == b.imag). Define these two operators to make this so. (Note: < is not standard in math; there is no natural ordering mathematically for complex numbers. However, we will allow it to be defined this way in the problem.)

Pass all Complex parameters as const & and return all values of functions that sensibly return complex numbers (like operator+(), e.g.) as Complex values (not & parameters).

What to Turn In

To avoid Canvas adding a number to your complex files (i.e. same names as lab 5) prepend your initials.  

For example:  Ann Ohlone would be handing in the 3 files: aocomplex.h, aocomplex.cpp, a6.cpp

Hand in 3 files: No zip files.

  • yourinitialscomplex.h : interface file
  • yourinitialscomplex.cpp : implementation file
  • a6.cpp : test driver file

Solutions

Expert Solution

operator (keyword) : Defines a new action
Syntax:
operator <operator symbol>( <parameters> )
{
<statements>;
}

The keyword "operator", followed by an operator symbol, defines a new
(overloaded) action of the given operator.

Example:
complex operator +(complex c1, complex c2)
{
return complex(c1.real + c2.real, c1.imag + c2.imag);
}
Operator functions are same as normal functions. The only differences are, name of an operator function is always operator keyword followed by symbol of operator and operator functions are called when the corresponding operator is used.

  • For operator overloading to work, at least one of the operands must be a user defined class object.
  • Compiler automatically creates a default assignment operator with every class. The default assignment operator does assign all members of right side to the left side and works fine most of the cases.
  • Overloaded conversion operators must be a member method. Other operators can either be member method or global method.
  • Any constructor that can be called with a single argument works as a conversion constructor, means it can also be used for implicit conversion to the class being constructed.

C++ program to overload different operators and apply on complex numbers(real and imaginary) :

#include<iostream.h>
#include<conio.h>

class complex
{
   double real;   // Real Part
   double imag; // Imaginary part
public:
   complex() { } // Constructor1
   complex(double x,double y) // Constructor2
   {
       real=x; imag=y;
   }
   complex operator+(complex);
   complex operator-(complex);
   complex operator*(complex);
   complex operator/(complex);
   void toString(void);
};
complex complex::operator+(complex c)
{
   complex temp;           // Temporary
   temp.real=real+c.real;       // Float Addition
   temp.imag=imag+c.imag;       // Float Addition
   return(temp);
}
complex complex::operator-(complex c)
{
   complex temp;
   temp.real=real-c.real;
   temp.imag=imag-c.imag;
   return(temp);
}
complex complex::operator*(complex c)
{
   complex temp;
   temp.real=real*c.real-imag*c.imag;
   temp.imag=real*c.imag+imag*c.real;
   return(temp);
}
complex complex::operator/(complex c)
{
   complex temp;
   if(((c.real*c.real)+(c.imag*c.imag))!=0 && ((c.real*c.real)+(c.imag*c.imag))!=0)
   {
       temp.real=((real*c.real)+(imag*c.imag))/((c.real*c.real)+(c.imag*c.imag));
       temp.imag=((imag*c.real)-(real*c.imag))/((c.real*c.real)+(c.imag*c.imag));
   }
   else
       cout<<"Cannot Divide By Zero";
   return(temp);
}
void complex::toString(void)
{
   cout<<real<<" , "<<imag<< "\n";
}
int main()
{
   clrscr();
   complex C1,C2,C3;   // Invokes Constructor 1
   C1=complex(2.5,3.4);   // Invokes Constructor 2
   C2=complex(1.6,2.7);   // Invokes Constructor 3
   C3=C1+C2;

   cout<<"C1 = ";C1.toString();
   cout<<"C2 = ";C2.toString();
   cout<<"Complex Addition = ";C3.toString();

   C1=complex(2.5,3.6);
   C2=complex(1.6,2.9);
   C3=C1-C2;
   cout<<"C1 = ";C1.toString();
   cout<<"C2 = ";C2.toString();
   cout<<"Complex Substraction = ";C3.toString();

   C1=complex(1,2);
   C2=complex(3,4);
   C3=C1*C2;
   cout<<"C1 = ";C1.toString();
   cout<<"C2 = ";C2.toString();
   cout<<"Complex Multiplication = ";C3.toString();

   C1=complex(1,2);
   C2=complex(3,4);
   C3=C1/C2;
   cout<<"C1 = ";C1.toString();
   cout<<"C2 = ";C2.toString();
   cout<<"Complex Division = ";C3.toString();
   getch();
   return 0;
}

OUTPUT



Related Solutions

Lab Assignment Objectives 'Be able to overload combined binary operators as member operator functions. Show how...
Lab Assignment Objectives 'Be able to overload combined binary operators as member operator functions. Show how to overload binary operators as friend functions. Show how to convert from a fundamental type to a user-defined type using a constructor. Understand exception handling mechanisms using try-catch block statements. Understand the Application Complex Numbers A complex number, c, is an ordered pair of real numbers (doubles). For example, for any two real numbers, s and t, we can form the complex number: This...
C++ Programming 19.2 Operator Overloading practice Write the prototypes and functions to overload the given operators...
C++ Programming 19.2 Operator Overloading practice Write the prototypes and functions to overload the given operators in the code main.cpp //This program shows how to use the class rectangleType. #include <iostream> #include "rectangleType.h" using namespace std; int main() { rectangleType rectangle1(23, 45); //Line 1 rectangleType rectangle2(12, 10); //Line 2 rectangleType rectangle3; //Line 3 rectangleType rectangle4; //Line 4 cout << "Line 5: rectangle1: "; //Line 5 rectangle1.print(); //Line 6 cout << endl; //Line 7 cout << "Line 8: rectangle2: "; //Line...
This chapter uses the class rectangleType to illustrate how to overload the operators +, *, ==,...
This chapter uses the class rectangleType to illustrate how to overload the operators +, *, ==, !=, >>, and <<. In this exercise, first redefine the class rectangleType by declaring the instance variables as protected and then overload additional operators as defined in parts a to c. 1.Overload the pre- and post-increment and decrement operators to increment and decrement, respectively, the length and width of a rectangle by one unit. (Note that after decrementing the length and width, they must...
Show that Hermitian operators have real eigenvalues. Show that eigenvectors of a Hermitian operator with unique...
Show that Hermitian operators have real eigenvalues. Show that eigenvectors of a Hermitian operator with unique eigenvalues are orthogonal. Use Dirac notation for this problem.
Overloading the insertion (<<) and extraction (>>) operators for class use requires creating operator functions that...
Overloading the insertion (<<) and extraction (>>) operators for class use requires creating operator functions that use these symbols but have a parameter list that includes a class ____. object address reference data type Flag this Question Question 210 pts When overloading the insertion operator to process a Complex object, it’s important to understand that you’re overloading an operator in the ____ class. istream operator Complex ostream Flag this Question Question 310 pts ____ class variables are allocated memory locations...
Lab Objectives Be able to declare a new class Be able to write a constructor Be...
Lab Objectives Be able to declare a new class Be able to write a constructor Be able to write instance methods that return a value Be able to write instance methods that take arguments Be able to instantiate an object Be able to use calls to instance methods to access and change the state of an object Introduction Everyone is familiar with a television. It is the object we are going to create in this lab. First we need a...
In class we discussed how to overload the + operator to enable objects of type Fraction to be added together using the + operator.
2.(a) Fraction Operators Objective:In class we discussed how to overload the + operator to enable objects of type Fraction to be added together using the + operator. Extend the Fraction class definition so that the -, * and / operators are supported. Write a main function that demonstrates usage of all of these operators.(b)More Custom Types Objective:Define a set of classes that represent a Schedule and Course in the context of a university student who has a schedule with a...
6.28 LAB: Convert to binary - functions Write a program that takes in a positive integer...
6.28 LAB: Convert to binary - functions Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is: As long as x is greater than 0 Output x % 2 (remainder is either 0 or 1) x = x / 2 Note: The above algorithm outputs the 0's and 1's in reverse order. You will need to write a second...
Wondering where to start on this C++ homework assignment involving friend functions and overloading operators implemented...
Wondering where to start on this C++ homework assignment involving friend functions and overloading operators implemented in a Rational class. These are the instructions: Your class will need to store two internal, integer values for each Rational number, the numerator (top) and denominator (bottom) of the fraction. It will have three constructor functions, with zero, one and two arguments, used as follows:     Rational test1, test2(10), test3(1, 2); The declaration for test1 calls the default (no argument) constructor, which should...
// Lab Homework 11 // Logical Operator AND and OR // Demonstrate how to use a...
// Lab Homework 11 // Logical Operator AND and OR // Demonstrate how to use a logical operator // with a Boolean expression. #include <iostream> #include <cctype> // for tolower() using namespace std; int main() {    int numberOfCreditHours; // Number of credit hours student has completed    float gpa; // The student's cumulative grade point average    // Ask the user two questions:    cout << "Answer the following questions:" << endl << endl;    cout << "How many...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT