头文件:
#ifndef COMPLEX_H_
#define COMPLEX_H_
class Complex0
{
private:
double real;
double imaginary;
public:
//construction
Complex0();
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 );
Complex0 operator-( const Complex0 &a );
Complex0 operator*( const Complex0 &a );
Complex0 operator*( double m );
}
#endif
函数实现:
#include <iostream>
using namespace std;
#include "complex.h"
Complex0::Complex0()
{
real = 0.0;
imaginary = 0.0;
}
Complex0::Complex0( double rea , double ima )
{
real = real;
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 )
{
Complex0 ccc;
ccc.real = real + a.real;
ccc.imaginary = imaginary + a.imaginary;
return ccc;
}
Complex0 Complex0::operator-( const Complex0 &a )
{
Complex0 ccc;
ccc.real = real - a.real;
ccc.imaginary = imaginary - a.imaginary;
return ccc;
}
Complex0 Complex0::operator*( const Complex0 &a )
{
Complex0 ccc;
ccc.real = real * a.real - imaginary * a.imaginary;
ccc.imaginary = real * a.imaginary + imaginary * a.real;
return ccc;
}
Complex0 Complex0::operator*( double m )
{
Complex0 ccc;
ccc.real = m * real;
ccc.imaginary = m * imaginary;
return ccc;
}
主函数:
#include <iostream>
using namespace std;
#include "complex.h"
int main (void)
{
Complex0 a( 3.0, 4.0 );
Complex0 c;
cout << "Enter a complex number (q to quit )";
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`!";
return 0;
}