c++中複數的遞增與遞減操作實現

來源:互聯網
上載者:User

  在標準C++中,實際上是不提供對複數類型遞增與遞減操作符的支援,複數包含實數與虛數兩部分。我通過重載了複數的操作符來實現遞增與遞減操作。

   

  遞增與遞減操作都是針對複數的實部來實現的。比如complex<double> cval; cval++只是針對複數實部加1.

下面是我的詳細實現:

   先看看前置操作符的實現形式,是通過引用來進行的,非常簡單。

#include "stdafx.h"
#include <complex>
using namespace std;

inline complex<double>& operator++(complex<double> &val)
{
    return val+=complex<double>(1);
}

  後置操作符的形式與前置類似,為了與前置操作符區分,加了另外一個參數,int類型的,這隻是一個額外參數,沒什麼其它的意義,與前置操作符不同的是,函數的傳回值是以傳值的方式進行的,而不是以引用的方式傳遞,只是簡單返回原值。

#include "stdafx.h"
#include <complex>
using namespace std;

inline complex<double> operator++(complex<double>&val,int i)
{
    complex<double> oldval = val;
    val += complex<double>(1);
    return oldval;
}

  這兩種實現方式非常簡單,下面我通過測試程式進行測試:

#include "stdafx.h"
#include <iostream>
#include <complex>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    complex<double> cval(4.0,1.0);
    cout << "before increment:" <<cval<<endl;
    cout << "after increment++:" <<cval++ <<endl; 
    cout <<"after ++increment:" << ++cval <<endl;
    cout << "after increment--:" <<cval-- <<endl; 
    cout <<"after --increment:" << --cval <<endl;

    //wait input
    int exit;
    cin >> exit;
    return 0;
}

 

   遞減操作符我就不多講了,都差不多!忘了今天是Christmas, 對自己說聲:Merry Christmas!

 

 

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.