欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來(lái)到入門教程網(wǎng)!

C語(yǔ)言

當(dāng)前位置:主頁(yè) > 軟件編程 > C語(yǔ)言 >

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

來(lái)源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語(yǔ)言|點(diǎn)擊: 次

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

用轉(zhuǎn)換構(gòu)造函數(shù)可以將一個(gè)指定類型的數(shù)據(jù)轉(zhuǎn)換為類的對(duì)象。但是不能反過(guò)來(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è)問(wèn)題。類型轉(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í)間空間開(kāi)銷。

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

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

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有