/*
CS371p: Quiz #20 (5 pts)
*/
/* -----------------------------------------------------------------------
1. Operators have the following properties.
a. precedence
b. associativity
c. arity (number of arguments)
d. lvalue / rvalue nature of the arguments or return
Which of those properties can be changed when overloading the operator
on a user type?
(Maybe more than one.)
(2 pts)
d.
*/
/* -----------------------------------------------------------------------
2. Define class Complex such that the program below works.
The operator+() MUST call the operator+=().
(2 pts)
*/
#include <cassert> // assert
template <typename T>
class Complex {
private:
T _r;
T _i;
public:
Complex (const T& r = T(), const T& i = T()) :
_r (r),
_i (i)
{}
Complex& operator += (const Complex& rhs) {
_r += rhs._r;
_i += rhs._i;
return *this;}
const T& real () const {
return _r;}
const T& imag () const {
return _i;}};
template <typename T>
Complex<T> operator + (Complex<T> lhs, const Complex<T>& rhs) {
return lhs += rhs;}
int main () {
Complex<int> x(2, 3);
const Complex<int> y(4, 5);
const Complex<int>& z = (x += y);
assert(&z == &x);
assert(z.real() == 6);
assert(z.imag() == 8);
Complex<int> t = y + z;
assert(t.real() == 10);
assert(t.imag() == 13);
return 0;}
syntax highlighted by Code2HTML, v. 0.9.1