1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
|
#include <iostream>
#include <fstream>
using namespace std;
ifstream infile ("in.dat");
class complx
{
double real, imag;
public:
complx( double real = 0., double imag = 0.); // constructor
//complx::~complx(); // destructor
//Sets private data members.
void Set(double new_real, double new_imaginary)
{
real = new_real;
imag = new_imaginary;
}
//Returns the real part of the complex number.
double Real()
{
return real;
}
//Returns the imaginary part of the complex number.
double Imaginary()
{
return imag;
}
};
/* I/O Function declarations */
ostream &operator << ( ostream &out_file, complx number );
extern istream &operator >> ( istream &in_file, complx &number );
extern ifstream &operator >> ( ifstream &in_file, complx &number );
/* External Function */
complx &operator + (double, complx);
int main()
{
int i=0;
complx in[6];
double d = 4.5;
cout<< "The input numbers are: " << endl;
while (infile >> in[i])
{
cout << in[i] << endl;
i++;
}
complx s2 = d + in[2]; // overload operator+()
cout << "The sum is a complex number " << s2 <<endl;
char pause; cin >> pause;
return 0; //successful termination
}
// constructor
complx::complx( double r, double i )
{
real = r; imag = i;
}
// destructor
////complx::~complx()
////{
// real = 0;
//// imag = 0;
//}
/*------- Non Member Function -------*/
complx &operator + (double d, complx c)
{
cout << "\n\n&operator +";
cout << "\nc.Real is " << c.Real();
cout << "\nc.Imaginary is " << c.Imaginary();
cout << "\nd is " << d;
complx result;
result.Set( d + c.Real(), c.Imaginary() );
cout << "\nresult is " << result << "\n\n";
return result;
}
/*------- I/O stream -------*/
extern ifstream &operator >> ( ifstream &in_file, complx &number )
{
double re, is;
char ch;
if (in_file >> ch && ch == '('&& in_file >> re >> ch && ch == ','
&& in_file >> is >> ch && ch == ')')
number.Set(re,is);
else cerr << "Finish the input"<<endl;
return in_file;
}
extern istream &operator >> ( istream &in_file, complx &number )
{
double re, is;
char ch;
if (in_file >> ch && ch == '('&& in_file >> re >> ch && ch == ','
&& in_file >> is >> ch && ch == ')')
number.Set(re,is);
else cerr << "Finish the input"<<endl;
return in_file;
}
ostream &operator<< ( ostream &out_file, complx number )
{
out_file << '(' << number.Real() << ',' << number.Imaginary() << ')';
return out_file;
}
|