cpp: complex 的简易实现

加深对操作符重载的熟悉程度…

//
// Created by cat on 2018/1/1.
//

#ifndef CPP02_COMPLEX0_H
#define CPP02_COMPLEX0_H


#include 

namespace complex0 {

    class Complex {
    private:
        double realNum;
        double imaginaryNum;
    public:
        explicit Complex(double realNum = 0, double imaginaryNum = 0);

        virtual ~Complex();

        // inline getter
        double getImaginaryNum() const { return imaginaryNum; };

        double getRealNum() const { return realNum; };

        //  operator
        friend Complex operator+(const Complex &a, const Complex &b);

        friend Complex &operator+=(Complex &a, const Complex &b);

        friend Complex operator-(const Complex &a, const Complex &b);

        friend Complex &operator-=(Complex &a, const Complex &b);

        friend Complex operator*(double factor, const Complex &obj);

        friend Complex &operator*=(double factor, Complex &obj);


        friend Complex operator*(const Complex &a, const Complex &b);

        friend Complex &operator*=(Complex &a, const Complex &b);

        Complex operator~() const;

        // io
        friend std::ostream &operator<<(std::ostream &os, const Complex &cp);

        friend std::istream &operator>>(std::istream &iis,  Complex &cp);
    };

};


#endif //CPP02_COMPLEX0_H
std::istream &operator>>(std::istream &iis, Complex &cp) {
        double xx;
//        std::stringstream ss;
//        std::string input;
//        getline(iis, input);
        if (iis >> xx) {
            cp.realNum = xx;
        } else {
            return iis;
        }

        if (iis >> xx) {
            cp.imaginaryNum = xx;
        } else {
            return iis;
        }
//        iis >> cp.realNum;
//        iis >> cp.imaginaryNum;
        iis.clear();
        return iis;
    }
#include 
#include 

#include "complex0.h"
#include 
using namespace std;

int main() {

    using complex0::Complex;
    Complex a(3, 4);
    Complex c;

    stringstream ss;
    int x;
    ss >> x;

    cout << "x = " << x;
    cout << "Enter a complex number(q to quit):\n";

    while (cin >> c) { // #####--####
        cout << "c is " << c << "\n";
        cout << "complex conjugate is " << ~c << '\n';
        cout << "a is " << a << '\n';
        cout << "a + c is " << a + c << '\n';
        cout << "a - c is " << a - c << '\n';
        cout << "a * c is " << a * c << '\n';
        cout << "2 * c is " << 2 * c << '\n';
        cout << "Enter a complex number(q to quit):\n";
    }
    cout << "Done!\n";
    return 0;
}

ps: 控制台输入的确是个麻烦的玩意啊~。

你可能感兴趣的:(computer,大猫学C/C++)