急!C++定义一个复数类Complex,使下面的代码能够工作?

2025-02-25 10:46:31
推荐回答(2个)
回答1:

#include 

using namespace std;

class Complex

{

private:

    double re;

    double im;

public:

    Complex(double re,double im=0){

        this->re = re;

        this->im = im;

    }

    void add(const Complex& c){

        this->re += c.re;

        this->im += c.im;

    }

    void sub(const Complex& c){

        this->re -= c.re;

        this->im -= c.im;

    }

    void show(){

        if(this->re==0)

            cout << this->im << "i" << endl;

        if(this->im==0)

            cout << this->re << endl;

        if(this->im!=0 && this->im<0)

            cout << this->re << this->im << "i" << endl;

        if(this->im!=0 && this->im>0)

            cout << this->re << "+" << this->im << "i" << endl;

    }

};

int main()

{

    double re,im;

    cin >> re >> im;

    Complex c1(re,im);

    cin >> re;

    Complex c2 = re;

    c1.show();

    c2.show();

    c1.add(c2);

    c1.show();

    c2.sub(c1);

    c2.show();

    return 0;

}

回答2:

供参考:
//////////////////头文件
#include
class Complex
{
public:
Complex(double r, double i);
Complex(Complex& c);
Complex(double r);
Complex& add(Complex& c);
Complex& sub(Complex& c);
void show(std::ostream& os=std::cout);
private:
double r, i;
};
/////////////////////////////cpp
#include "Complex.h"
Complex::Complex(double r, double i) :r(r), i(i) {}
Complex::Complex(Complex& c) : r(c.r), i(c.i) {}
Complex::Complex(double r) : r(r), i(0) {}
Complex& Complex::add(Complex& c)
{
r += c.r;
i += c.i;
return *this;
}
Complex& Complex::sub(Complex& c)
{
r -= c.r;
i -= c.i;
return *this;
}
void Complex::show(std::ostream& os)
{
if (r != 0 && i != 0)
{
os << r << (i > 0 ? "+": "-") << abs(i) << "i" << std::endl;
}
else if (r == 0)
{
os << i << "i" << std::endl;
}
else if (i == 0)
{
os << r << std::endl;
}
else
{
os << 0 << std::endl;
}
}