溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

淺談C++類型轉(zhuǎn)化(運(yùn)算符重載函數(shù))和基本運(yùn)算符重載(自增自減)

發(fā)布時(shí)間:2020-09-24 15:45:40 來(lái)源:腳本之家 閱讀:95 作者:jingxian 欄目:編程語(yǔ)言

類型轉(zhuǎn)化(運(yùn)算符重載函數(shù))

用轉(zhuǎn)換構(gòu)造函數(shù)可以將一個(gè)指定類型的數(shù)據(jù)轉(zhuǎn)換為類的對(duì)象。但是不能反過來(lái)將一個(gè)類的對(duì)象轉(zhuǎn)換為一個(gè)其他類型的數(shù)據(jù)(例如將一個(gè)Complex類對(duì)象轉(zhuǎn)換成double類型數(shù)據(jù))。在C++提供類型轉(zhuǎn)換函數(shù)(type conversion function)來(lái)解決這個(gè)問題。類型轉(zhuǎn)換函數(shù)的作用是將一個(gè)類的對(duì)象轉(zhuǎn)換成另一類型的數(shù)據(jù)。

類型轉(zhuǎn)換函數(shù)的一般形式為:

operator 類型名( ){
  實(shí)現(xiàn)轉(zhuǎn)換的語(yǔ)句
}

下面是簡(jiǎn)單實(shí)現(xiàn)。這時(shí)候,Base起了兩方面的作用:類和數(shù)據(jù)類型。系統(tǒng)會(huì)在需要的時(shí)候自動(dòng)調(diào)用對(duì)應(yīng)的類方法。

#include <iostream>
using namespace std;

class Base{
  private:
    float x;
    int y;
  public:
    Base (float xx=0,int yy=0){
      x = xx;
      y = yy;
    }
    operator float (){
      return x;
    }
    operator int (){
      return y;
    }
    void display(){
      cout<<"x is :"<<x<<";y is :"<<y<<endl;
    }
};

int main()
{
  Base base(1.0,2);
  base.display();
  int y= base;
  float x= base;
  cout<<"NewX is :"<<x<<"NewY is:"<<y<<endl;
  return 0;
}

基本運(yùn)算符重載(自增自減)

主要總結(jié) 自增自減的前置和后置的用法。其他的加減乘除較簡(jiǎn)單。

簡(jiǎn)單的代碼實(shí)現(xiàn)(純語(yǔ)法)

#include <iostream>
using namespace std;

class Base{
  private:
    float x;
    int y;
  public:
    Base (float xx=0,int yy=0){
      x = xx;
      y = yy;
    }
    operator float (){
      return x;
    }
    operator int (){
      return y;
    }
    Base operator ++(){//前置 ++
      x++;
      y++;
      return *this;
    } 
    Base operator --(){
      x--;
      y--;
      return *this;
    }
    Base operator ++(int ){//后置 ++
      Base temp = *this;
      ++(*this);
      return temp;
    }
    Base operator --(int ){
      Base temp = *this;
      --(*this);
      return temp;
    }
    void display(){
      cout<<"x is :"<<x<<";y is :"<<y<<endl;
    }
    
};

int main()
{
  Base base(1.0,1);
  Base tem = base++;
  base.display();
  tem.display(); 
  
  Base base2(1.0,1);
  tem = ++base2;
  base.display();
  tem.display(); 
  return 0;
}

發(fā)現(xiàn):

后置和前置的區(qū)別是有無(wú)int參數(shù)。

后置需要申請(qǐng)新的空間,大小是類的大小。所以,后置操作會(huì)有額外的時(shí)間空間開銷。

盡量使用前置操作:如:for (int i=0;i<n;++i)

以上這篇淺談C++類型轉(zhuǎn)化(運(yùn)算符重載函數(shù))和基本運(yùn)算符重載(自增自減)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI