home *** CD-ROM | disk | FTP | other *** search
- // **************************************************************
- // Complex.cpp
- // Example program for Simple C++
- //
- // (c) 1999 Emmenjay Consulting Pty Ltd
- //
- // History
- // 30/08/99 MJS Initial Coding.
- //
- // **************************************************************
-
- #include <iostream>
-
- class CComplex {
- private:
- double r, i;
- public:
- CComplex(void);
- CComplex(double r0, double i0);
- double Real(void);
- double Imag(void);
- void Set(double r0, double i0);
-
- };
-
- CComplex operator +(CComplex &c0, CComplex &c1)
- {
- CComplex c( c0.Real()+c1.Real(), c0.Imag()+c1.Imag() );
- return c;
- }
-
- CComplex operator +(CComplex &c0, double d)
- {
- CComplex c( c0.Real()+d, c0.Imag() );
- return c;
- }
-
- CComplex operator -(CComplex &c0, CComplex &c1)
- {
- CComplex c( c0.Real()-c1.Real(), c0.Imag()-c1.Imag() );
- return c;
- }
-
- CComplex operator *(CComplex &c0, CComplex &c1)
- {
- // (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
- CComplex c( c0.Real()*c1.Real() - c0.Imag()*c1.Imag(),
- c0.Real()*c1.Imag() + c0.Imag()*c1.Real() );
- return c;
- }
-
- CComplex operator /(CComplex &c0, CComplex &c1)
- {
- // (a + bi) / (c + di) = (ac + bd)/(c**2 + d**2) + ((bc - ad)/(c**2 + d**2))i
- double denom, re, im;
-
- denom = c1.Real()*c1.Real() + c1.Imag()*c1.Imag();
- re = (c0.Real()*c1.Real() + c0.Imag()*c1.Imag()) / denom;
- im = (c0.Imag()*c1.Real() - c0.Real()*c1.Imag()) / denom;
- CComplex c( re, im );
- return c;
- }
-
- ostream& operator <<(ostream &s, CComplex &c)
- {
- s << "(" << c.Real() << "," << c.Imag() << ")";
- return s;
- }
-
- CComplex::CComplex(void)
- {
- Set(0,0);
- }
-
- CComplex::CComplex(double r0, double i0)
- {
- Set(r0,i0);
- }
-
- double CComplex::Real(void)
- {
- return r;
- }
-
- double CComplex::Imag(void)
- {
- return i;
- }
-
- void CComplex::Set(double r0, double i0)
- {
- r=r0;
- i=i0;
- }
-
- int main(void)
- {
- CComplex c0(3.8,6.4);
- CComplex c1(2.3,5.1);
- CComplex c = c0-c1;
- std::cout << "c = " << c << '\n';
- c1 = c+3.0;
- std::cout << "c1 = " << c1 << '\n';
- return 0;
- }
-