# Problem 1 — Geometric Points with Operators

Download the file `code.zip` and add its content (the files `point.cpp`, `point.h`, `test.cpp`, `test.h`, `asserts.h`) to a new Code::Blocks project.

The class `Point` has already been defined for you. It models a geometric point of arbitrary dimension. It contains:

• a constructor that takes a vector of `double` and that initializes the point’s entries
• a member function `dimension()` that returns the number of entries
• an access operator `[]` that allows to access the `i`th entry of point `p` by writing `p[i]`. Note that indices in the class `Point` start at 1, and not at 0 like for vectors or arrays
• an operator `==` to test whether two points are equal

Take care not to change the points given as an argument. In particular, return a new point.

We begin by defining an addition operator for two geometric points.

Add an operator `+` that takes two (constant references to) `Point`s. It returns a `Point` whose entries are the sums of the arguments’ entries at the same index.

If the dimensions of the two points are not equal, throw an exception of type `invalid_argument`.

You can test your operator by executing the program whose `main` function is defined in the file `test.cpp`.

## b — Subtraction

We will now add a subtraction operator for two points. Its implementation will be similar to that of the addition operator.

Add an operator `+` that takes two (constant references to) `Point`s. It returns a `Point` whose entries are the differences of the arguments’ entries at the same index.

If the dimensions of the two points are not equal, throw an exception of type `invalid_argument`.

You can test your operator by executing the program whose `main` function is defined in the file `test.cpp`.

## c — Displaying a Point

You can look at the code shown in Lecture 3 for an example of an implementation of the operator `<<` for the class `Date`.

In particular, note that the first argument as well as the return value is of type `ostream &` (i.e., a reference to an output stream, like `cout` for example).

In order to be able to display our geometric points, we will add the operator `<<` so that we can write `cout << p << endl;` where `p` is an instance of the class `Point`.

Add an operator `<<` to display the entries of a point. Every entry of the point should be followed by a newline.

You can test your operator by executing the program whose `main` function is defined in the file `test.cpp`.

back to the course web site