Exercise 29
Info

This is an in-class exercise. An exercise page like this one will contain a brief description but is intended to be supplemented by discussion during our meeting time. Complete the exercise to the best of your ability in the time given. Feel free to talk with other students as you work, and do not be afraid to ask questions if you get stuck. Aim to complete as much as possible during our meeting. You are encouraged to work at home to complete what you do not get through today, and ask questions over Piazza or in office hours.

Learning Objectives

Reinforces concepts learned in today's meeting:

  • C++ classes, fields & member functions
  • Operator overloading
  • The friend keyword

Part 1

Pull the starter code for this exercise from the public repo by taking the following steps:

  1. Log into ugrad, navigate into our public repo, then type git pull to synchronize your local repo and working copy with the remote repo.

  2. Copy the files from the public class repository /exercises/ex29/ directory to your personal repo. Navigate to your personal repo copy – you should see files named Makefile, complex.[h/cpp], and main.cpp inside.

Part 2

The main purpose of this exercise is to complete the definition of a class to store and operate on complex numbers. Read the instructional comments in complex.h and complex.cpp to start, then review main.cpp. It shows an example of how to use the given code for the Complex class. You can compile and run the code using commands make main and ./main.

The first task is to overload and implement the operator<< function for printing complex objects. After your implementation, you can uncomment the related parts in main.c, compile and test your implementation. (Note: remember to use the friend keyword.)

Part 3

Follow the instructions in the comments in complex.h and complex.cpp to write some missing functions for which we have provided headers within the complex.h file. You should not change anything in the complex.h file. Try to not reinvent the wheel when writing the add functions. After your implementation, you can uncomment the related parts in main.c, compile and test your implementation.

Part 4

When we multiply a float with the Complex class, it will not work as we have not overloaded the operator* for the float. It can be done by adding a non-member function to allow a float to be multiplied by a Complex value. Finish the implementation in complex.cpp prototyped in complex.h. After your implementation, you can uncomment the related parts in main.c, compile and test your implementation.

Reminder

Remember to add and commit to your local repo copy as your work. Push to your remote repo when finished. [No need to submit to Gradescope to check your solution.] Use exit to logout from your ugrad account when finished. If you continue to work on the program after class, make sure to keep your repo updated as well!