c++複數類的實現
阿新 • • 發佈:2019-02-14
複數是一個數學中很重要的東西,下面是我用c++實現的複數的類
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; #include <cstdlib> class Plural { public: Plural(int real = 0, int image = 0) // 建構函式 : _real(real) , _image(image) { } ~Plural() //解構函式 { } Plural(const Plural &num) //拷貝建構函式 { _real = num._real; _image = num._image; } bool operator>(const Plural& num) //大於號的過載 { if (_image == 0 && num._image == 0) { if (_real > num._real) { return true; } else { return false; } } else { return false; } } bool operator<(const Plural& num) //小於號的過載 { if (_image == 0 && num._image == 0) { if (_real < num._real) { return true; } else { return false; } } else { return false; } } bool operator=(const Plural& num) //複製運算子的過載 { if (_real == num._real && _image == num._image) { return true; } else { return false; } } Plural operator+(const Plural num) //加號的過載 { Plural temp; temp._real = _real + num._real; temp._image = _image + num._image; return temp; } Plural operator-(const Plural num) // 減號的過載 { Plural temp; temp._real = _real - num._real; temp._image = _image - num._image; return temp; } Plural operator++(int) //後置加加 { return _real++; } Plural operator--(int) //後置減減 { return _real--; } Plural operator+=(const Plural num) //加等 { return _real += num._real; } Plural operator-=(const Plural num) //減等 { return _real -= num._image; } Plural operator*(const Plural num) //乘法 { Plural temp; temp._real = _real*num._real - _image*num._image; temp._image = _image*num._real + _real*num._image; return temp; } Plural operator/(const Plural num) //除法 { Plural temp; temp._real = ((_real * num._real + _image * num._image) / (num._real * num._real + num._image * num._image)); temp._image = ((_image * num._real - _real * num._image) / (num._real * num._real + num._image * num._image)); return temp; } friend ostream& operator<<(ostream& os, Plural& c); //輸出運算子的過載 private: int _real; int _image; }; ostream& operator<<(ostream& os, Plural& c) { os << c._real << "+" << c._image << "i"; return os; } int main() { Plural p1(3, 4); Plural p2(1, 2); Plural p3(1, 0); Plural p4(1, 0); cout << "p1=" << p1 << endl; cout << "p2=" << p2 << endl; cout << "p3=" << p3 << endl; cout << "p4=" << p4 << endl; cout << "p1" << "-" << "p2" << "=" <<(p1 - p2) << endl; cout << "p1" << "+" << "p2" << "=" << (p1 + p2) << endl; cout << "p1" << ">" << "p2" << "=" << (p1 > p2) << endl; cout << "p1" << "<" << "p2" << "=" << (p1 > p2) << endl; cout << "p1" << "=" << "p2" << "=" << (p1 = p2) << endl; cout << "p3" << "=" << "p4" << "=" << (p3 = p4) << endl; cout << "p1" << "++" << "=" << (p1++) << endl; cout << "p1" << "--" << "=" << (p1++) << endl; cout << "p1" << "+=" << "p2" << "=" << (p1+=p2) << endl; cout << "p1" << "-=" << "p2" << "=" << (p1-=p2) << endl; system("pause"); return 0; }