complex類

complex.h
複數的四則運算不懂得網上都有,直接貼代碼

#pragma once
#include<iostream>
using namespace std;
class Complex
{
public:
    //四個成員函數
    Complex(double real = 0.0, double image = 0.0)//構造函數  
    {
        cout << "Complex()" << endl;
        _real = real;
        _image = image;
    }
    Complex(const Complex& c)//拷貝構造函數 
    {
        cout << "Complex(const Complex& c)" << endl;
        _real = c._real;
        _image = c._image;
    }
    ~Complex()//析構函數 
    {
        cout << "~Complex()" << endl;
    }
    Complex& operator=(const Complex& c)//賦值操作符的重載 
    {
        cout << "Complex& operator=(const Complex& c)" << endl;
        if (this != &c)
        {
            _real = c._real;
            _image = c._image;
        }
        return *this;
    }
    void Display()
    {
        cout << _real << "-" << _image << endl;
    }
    //比較運算符  
    //c1>c2  
    bool operator>(const Complex& c)
    {
        return _real > c._real
            && _image > c._image;
    }
    bool operator==(const Complex& c)//比較兩個複數是否相等 
    {
        return _real == c._real&&_image == c._image;
    }
    //c1>=c2  
    bool operator>=(const Complex& c)
    {
        return *this > c || *this == c;
    }
    //c1<c2  
    bool operator<(const Complex& c)
    {
        return !(*this >= c);
    }
    //c1<=c2  
    bool operator<=(const Complex& c)
    {
        return !(*this>c);
    }
    //c1!=c2  
    bool operator!=(const Complex& c)
    {
        return !(*this == c);
    }
    //前置後置++和+/+=的實現  

    Complex& operator++()//前置++ 
    {
        this->_real += 1;
        return *this;
    }

    Complex operator++(int)//後置++
    {
        Complex tmp(*this);
        this->_real += 1;
        return tmp;
    }
    Complex operator+(const Complex& c)//加法,+匿名對象不用&返回  
    {
        Complex tmp(*this);
        tmp._real = this->_real + c._real;
        tmp._image = this->_image + c._image;
        return tmp;
    }


    Complex& operator+=(const Complex& c)//+=匿名對象用&返回this 
    {
        this->_real += c._real;
        this->_image += c._image;
        return *this;
    }
private:
    double _real;
    double _image;

};



test.h

#include"complex.h"
int main()
{
    Complex c1(2.0, 3.0);
    Complex c2 = c1 + 2.0;
    c2.Display();
    system("pause");
    return 0;
}

程序運行結果:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章