This exercise introduces classes in C++. It works with several files
in the directory ~p6720/exercises/intro_to_classes. Copy all of them to
a working directory.
The answer file is lab11.
Exercise 1.
A primitive complex class
This is an exercise in C++ classes. We will be working with a class
that allows one to do arithmetic with complex numbers. It is
primitive. There are a number of standard templates for this purpose,
but we will be playing with our own to understand how classes work.
First, look at mycomplex0.h and checkcmplx0.cc. Compile
checkcmplx0 and run it. In your answer file, answer these
questions:
- How does the main program define what is meant by "complex".
Hint: What does the "include" statement do?
- How would we define a complex variable "b" and set its real
and imaginary parts to -1 and 7, respectively?
- What happens if we remove public: in the header file
mycomplex0.h or change it to private:?
(Try compiling it to see.)
Exercise 2.
Adding constructors and accessors
Now look at the files mycomplex1.h and
checkcmplx1.cc. Compile checkcmplx1 and run it.
- The class defines two constructors. Which one is
being used to set the final value of a and b?
- Is a constructor being used with the statement complex a,b?
Which one? What value is being set? To check your answer,
in the header file mycomplex1.h, change
re = 0 to re = 4, delete the
line a = complex(5.,6.); in the main program,
compile it and run it. How did the result change?
- What happens if we say a = complex(7.)?
- Now that the members re and im are private,
how do we extract the real and imaginary parts?
Execise 3.
Adding arithmetic operations
Next, look at the files mycomplex.h and
checkcmplx.cc to see what they do. Then compile and run the
program checkcmplx. Check the answers with Maple. Note that
Maple represents complex numbers in the straightforward notation a
+ b*I.
Copy your program output to the answer file.