Complex number class

As an exercise I have to create a complex number class in the form of a + bi
where a is real and b imaginary.
I have a good idea of what to do, I have been asked to use a constructor with default values, they are 0 & 0i.
All good so far.

However the exercise goes on to say
"
Use double variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it’s declared. The constructor should contain default values in case no initializers are provided. Provide public member functions that perform the fol- lowing tasks:
a) Adding two Complex numbers: The real parts are added together and the imaginary parts are added together.
b) Subtracting two Complex numbers:The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.
c) Printing Complex numbers in the form (a, b), where a is the real part and b is the imaginary part.
"

Here's the thing, I can get the objects to do the addition and subtraction but using object1.getReal and object1.getImaginary etc
This is not what is asked. How can I get to instances of the same class use a member to function to add the private member variables together of different instances?

I hope I have explained it reasonably well lol


Thanks in advance, plus I'm a newbie!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Foo {
  int bar;
public:
  Foo() : bar( 0 ) {}
  Foo( int foo ) :  bar( foo ) {}

  // compound assignment
  Foo & operator+= ( const Foo & rhs )
  {
    this->bar += rhs.bar; // instances, members, ...
    return *this;
  }
 
  // friends defined inside class body are inline and are hidden from non-ADL lookup
  friend Foo operator+ ( Foo lhs, const Foo & rhs)
  {
    lhs += rhs; // reuse compound assignment
    return lhs;
  }
};


See http://en.cppreference.com/w/cpp/language/operators
Last edited on
Topic archived. No new replies allowed.