這是一個複數類,第一個自己設計的類。
/*complexL.h*/</p><p>#ifndef PLURAL_H_<br />#define PLURAL_H_<br />#include<iostream></p><p>class complex<br />{<br />private:<br />double m_r ; //實數<br />double m_u ; //虛數</p><p>public:<br />complex(double r = 0.0 ,double u = 0.0 ) { m_r = r ; m_u = u ;}<br />~complex() {} </p><p>//operator overloading </p><p>complex operator+(complex &t) ;<br />complex operator-(complex &t) ;<br />complex operator*(complex &t) ;<br />complex operator~(void) ;</p><p>//friends</p><p>friend complex operator*(double x , complex &t) ;<br />friend complex operator*(complex &t ,double x) ;<br />friend std::ostream & operator << (std::ostream & os, const complex &c) ;<br />friend std::istream & operator >> (std::istream & is, complex &c) ;</p><p>} ;</p><p>#endif
/*complexL.cpp*/<br />#include<iostream><br />#include"Plural.h"</p><p>//operator overloading </p><p>complex complex::operator+(complex &t)<br />{<br />return complex(m_r + t.m_r , m_u + t.m_u) ; //調用建構函式<br />}</p><p>complex complex::operator-(complex &t)<br />{<br />return complex(m_r - t.m_r , m_u - t.m_u) ;<br />}</p><p>complex complex::operator*(complex &t)<br />{<br />return complex(m_r * t.m_r - m_u * t.m_u , m_r * t.m_u + m_u * t.m_r ) ;<br />}</p><p>complex complex::operator~(void)<br />{<br />return complex(m_r,-m_u) ;<br />}</p><p>//friends</p><p>complex operator*(double x , complex &t)<br />{<br />return t * complex(x) ;<br />}</p><p>std::ostream & operator << (std::ostream & os, const complex &c)<br />{<br />os << "( " << c.m_r << "," << c.m_u << "i)/n" ;<br />return os ;<br />}</p><p>std::istream & operator >> (std::istream & is, complex &c)<br />{<br />using std::cout ;<br />cout << "real : " ;<br />if((is >> c.m_r))<br />{<br />cout << "imaginary: " ;<br />is >> c.m_u ;<br />}</p><p>return is ; //如果錯誤輸入的話,則會留下一個錯誤標誌<br />}
/*complexTest.cpp*/</p><p>#include<iostream><br />#include"Plural.h"</p><p>using namespace std ;</p><p>int main(void)<br />{</p><p>complex a(3.0,4.0) ;<br />complex c ;<br />cout << "Enter a complex number (q to quit) : /n" ;<br />while(cin >> c)<br />{<br />cout << "c is " << c << '/n' ;<br />cout << "complex xonjugat is " << ~c << '/n' ;<br />cout << "a is " << a << '/n' ;<br />cout << "a + c is " << a+c << '/n' ;<br />cout << "a - c is " << a-c << '/n' ;<br />cout << "a * c is " << a*c << '/n' ;<br />cout << "2 * c is " << 2*c << '/n' ;<br />cout << "Enter a complex number(q to quit) : /n" ;<br />}</p><p>cout << "Done ! /n" ;<br />return 0 ;<br />}<br />