|
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- class Complex0
- {
- private:
- double real;
- double imaginary;
- public:
- //construction
- Complex0( double rea = 0.0, double ima = 0.0 );
- ~Complex0();
- // set real,imag from coordinate.
- void setReal( double rea );
- void setImag( double ima );
- Complex0 operator+( const Complex0 &a ) const;
- Complex0 operator-( const Complex0 &a ) const;
- Complex0 operator-() const;
- Complex0 operator*( const Complex0 &a ) const;
- Complex0 operator*( double m ) const;
- friend ostream & operator<<(ostream & os, const Complex0 & c);
- friend istream & operator>>(std::istream & is, Complex0 & c);
- };
- /*Complex0::Complex0()
- {
- real = 0.0;
- imaginary = 0.0;
- }*/
- Complex0::Complex0(double rea , double ima )
- {
- real = rea;
- imaginary = ima;
- }
- Complex0::~Complex0()
- {
- cout << "Bye1" << endl;
- }
- // set real,imag from coordinate.
- void Complex0::setReal( double rea )
- {
- real = rea;
- }
- void Complex0::setImag( double ima )
- {
- imaginary = ima;
- }
- Complex0 Complex0::operator+( const Complex0 & a) const
- {
- return Complex0(real+a.real, imaginary+a.imaginary);
- }
- Complex0 Complex0::operator-( const Complex0 &a ) const
- {
- return Complex0(real - a.real, imaginary - a.imaginary);
- }
- Complex0 Complex0::operator-() const
- {
- return Complex0(-real, -imaginary);
- }
- Complex0 Complex0::operator*( const Complex0 & a) const
- {
- return Complex0(real*a.real - imaginary*a.imaginary,
- real*a.imaginary + imaginary*a.real);
- }
- Complex0 Complex0::operator*( double m ) const
- {
- return Complex0(m * real, m * imaginary);
- }
- ostream & operator<<(ostream & os, const Complex0 & c)
- {
- if(c.imaginary > 0)
- os<<c.real<<"+i"<<c.imaginary;
- else if(c.imaginary == 0)
- os<<c.real;
- else
- os<<c.real<<"-i"<<-c.imaginary;
- return os;
- }
- istream & operator>>(std::istream & is, Complex0 & c)
- {
- if(is>>c.real)
- {
- if(is>>c.imaginary)
- return is;
- else
- {
- exit(1);
- }
- }
- else
- {
- exit(1);
- }
- }
- int main (void)
- {
- Complex0 a(3.0, 4.0);
- Complex0 c;
- cout << "Enter a complex number (q to quit )\n";
- while( cin >> c )
- {
- cout << "c is "<< c << endl;
- cout << "complex conjugate is " << -c << endl;
- cout << "a is "<< a << endl;
- cout <<"a + c = "<<a + c << endl;
- cout << "Enter a complex number (q to quit)";
- }
- cout << "Bye`!";
- system("pause");
- return 0;
- }
复制代码 |
|