欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++隱式類型轉(zhuǎn)換運(yùn)算符operator type()用法詳解

 更新時(shí)間:2020年06月22日 10:48:26   作者:Gesündeste  
這篇文章主要介紹了C++隱式類型轉(zhuǎn)換運(yùn)算符operator type()用法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

在閱讀<<C++標(biāo)準(zhǔn)庫>>的時(shí)候,在for_each()章節(jié)遇到下面代碼,

#include "algostuff.hpp"

class MeanValue{
private:
  long num;
  long sum;
public:
  MeanValue():num(0),sum(0){
  }

  void operator() (int elem){
    num++;
    sum += elem;
  }
  operator double(){
    return static_cast<double>(sum) / static_cast<double>(num);
  }
};

int main()
{
  std::vector<int> coll;
  INSERT_ELEMENTS(coll,1,8);
  double mv = for_each(coll.begin(),coll.end(),MeanValue()); //隱式類型轉(zhuǎn)換 MeanValue轉(zhuǎn)化為double
  std::cout<<"mean calue: "<< mv <<std::endl;
}

對(duì)于類中的operator double(){},第一次見到這個(gè)特別的函數(shù),其實(shí)他是"隱式類型轉(zhuǎn)換運(yùn)算符",用于類型轉(zhuǎn)換用的.

在需要做數(shù)據(jù)類型轉(zhuǎn)換時(shí),一般顯式的寫法是:

type1 i;
type2 d;
i = (type1)d; //顯式的寫類型轉(zhuǎn),把d從type2類型轉(zhuǎn)為type1類型

這種寫法不能做到無縫轉(zhuǎn)換,也就是直接寫 i = d,而不需要顯式的寫(type1)來向編譯器表明類型轉(zhuǎn)換,要做到這點(diǎn)就需要“類型轉(zhuǎn)換操作符”,“類型轉(zhuǎn)換操作符”可以抽象的寫成如下形式:

operator type(){};

只要type是一個(gè)類型,包括基本數(shù)據(jù)類型,自己寫的類或者結(jié)構(gòu)體都可以轉(zhuǎn)換。

隱式類型轉(zhuǎn)換運(yùn)算符是一個(gè)特殊的成員函數(shù):operator 關(guān)鍵字,其后跟一個(gè)類型符號(hào)。你不用定義函數(shù)的返回類型,因?yàn)榉祷仡愋途褪沁@個(gè)函數(shù)的名字。

1.operator用于類型轉(zhuǎn)換函數(shù):

類型轉(zhuǎn)換函數(shù)的特征:

1) 型轉(zhuǎn)換函數(shù)定義在源類中;

2) 須由 operator 修飾,函數(shù)名稱是目標(biāo)類型名或目標(biāo)類名;

3) 函數(shù)沒有參數(shù),沒有返回值,但是有return 語句,在return語句中返回目標(biāo)類型數(shù)據(jù)或調(diào)用目標(biāo)類的構(gòu)造函數(shù)。

類型轉(zhuǎn)換函數(shù)主要有兩類:

1) 對(duì)象向基本數(shù)據(jù)類型轉(zhuǎn)換:

#include<iostream>
#include<string>
using namespace std;
 
class D{
public:
  D(double d):d_(d) {}
  operator int() const{
    std::cout<<"(int)d called!"<<std::endl;
    return static_cast<int>(d_);
  }
private:
  double d_;
};
 
int add(int a,int b){
  return a+b;
}
 
int main(){
  D d1=1.1;
  D d2=2.2;
  std::cout<<add(d1,d2)<<std::endl;
  system("pause");
  return 0;
}

2)對(duì)象向不同類的對(duì)象的轉(zhuǎn)換:

#include<iostream>
class X;
class A
{
public:
  A(int num=0):dat(num) {}
  A(const X& rhs):dat(rhs) {}
  operator int() {return dat;}
private:
  int dat;
};
 
class X
{
public:
  X(int num=0):dat(num) {}
  operator int() {return dat;}
  operator A(){
    A temp=dat;
    return temp;
  }
private:
  int dat;
};
 
int main()
{
 X stuff=37;
 A more=0;
 int hold;
 hold=stuff;
 std::cout<<hold<<std::endl;
 more=stuff;
 std::cout<<more<<std::endl;
 return 0;
}

上面這個(gè)程序中X類通過“operator A()”類型轉(zhuǎn)換來實(shí)現(xiàn)將X類型對(duì)象轉(zhuǎn)換成A類型。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論