开发者

Implement complex number's class in C++

开发者 https://www.devze.com 2023-01-13 22:10 出处:网络
Here I am trying to implement a class for complex numbers using books and the Internet. Here is the code:

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  Compl开发者_运维百科ex{
    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?


#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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消