1

Here I am trying to implement a class for complex numbers using books and the Internet. Here is the code:

#include <iostream>
#include <ostream>
using namespace std;
class  Complex{
    private:
        float re,im;

    public:
        Complex(float x,float y){
            re=x;
            im=y;
        }

        float Re() const{
            re;
        }

        float Im() const {
            return  im;
        }

        Complex&  operator*=(const Complex& rhs){
            float t=Re();
            re = Re()*rhs.Re()-Im()*rhs.Im();

            im = t*rhs.Im()+Im()*rhs.Re();
            return *this;
        }
};

ostream& operator<<(ostream& t,const Complex& c){
    t << c.Re() << " " << c.Im(); 
    return t;
}

int main(){
    Complex s(3.45,23.12);
    return 0;
}

It compiles fine, but I can't find a way to print the real and imaginary parts of the number on the screen?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • In main, just before you return, put "cout << s << '\n';". std::cout is the "standard output" / terminal / screen / tty device. '\n' represents a newline, saying the line is complete and please move to the next one. It's always best to end your output with a newline, so some other program that moves the cursor back to the start of the line doesn't overwrite and hide it (UNIX/Linux shells tend to do this). – Tony Delroy Aug 27 '10 at 09:54
  • 6
    Did you take a look at `std::complex` ? – ereOn Aug 27 '10 at 10:00
  • @Ian: There's an `operator<<()`. – sbi Aug 27 '10 at 10:34

3 Answers3

2
#include <iostream>

// ...

Complex s(3.45,23.12);
std::cout << s; 

See this answer for why I think using namespace std; is a bad idea.

Also, I suppose implementing a class for complex numbers is an exercise? Because the standard library already has one.

Community
  • 1
  • 1
sbi
  • 219,715
  • 46
  • 258
  • 445
0

See the header <complex> which implements std::complex… which you might want to use, unless you want to implement this as an exercise.

Here is a link to the GCC header file; all the basic operations are pretty simply implemented.

As for printing on screen, what is going wrong? Your operator<< looks fine.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
0

The solution above will work. I would however change the << implementation to be the following to get a more readable output (if that's what you want):

t<<c.Re()<< "  + i"<<c.Im(); return t;

In my opinion, this will show the representation in a clearer way.

sbi
  • 219,715
  • 46
  • 258
  • 445
Johan
  • 1