How would you express the addition of two complex numbers without code?
Then try to translate that into code.
(And keep in mind what you intend to do: add to the current object, or add two distinct objects and return a third.)
[And you can edit your post to add the missing closing tag: [/code].]
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
You're working in C++. C++ has operator overloading.
You're working on a mathematical addition operation. It makes in this context perfect sense to define an operator in (or as a friend of) your complex class.
As a start I'll give you the headerfile for a complex number class I implemented for fun a while ago.
The implementation of the methods and operator is trivial and I leave that to you.
#include <iostream>
using namespace std;
class complexNumber
{
private:
float real;
float imag;
public:
complexNumber();
complexNumber(float rPart, float iPart);
~complexNumber();
complexNumber operator+(const complexNumber& c);
complexNumber operator-(const complexNumber& c);
friend ostream& operator<<(ostream& s, const complexNumber& c);
};
When properly implemented you can use the following testcode on it:
#include "complexnum.h"
int main()
{
complexNumber t(1, 1);
complexNumber t2(2, 2);
complexNumber t3 = t + t2;
cout << t << endl << t2 << endl << t3;
return 0;
}
As you see I created not just a + operator but also a << operator so I can output a complex number directly and consistently.
The output of that small program should be1+i
2+2i
3+3i
jwenting
duckman
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337