C++隱式類型轉(zhuǎn)換運算符operator type()用法詳解
在閱讀<<C++標(biāo)準(zhǔn)庫>>的時候,在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; }
對于類中的operator double(){},第一次見到這個特別的函數(shù),其實他是"隱式類型轉(zhuǎn)換運算符",用于類型轉(zhuǎn)換用的.
在需要做數(shù)據(jù)類型轉(zhuǎn)換時,一般顯式的寫法是:
type1 i;
type2 d;
i = (type1)d; //顯式的寫類型轉(zhuǎn),把d從type2類型轉(zhuǎn)為type1類型
這種寫法不能做到無縫轉(zhuǎn)換,也就是直接寫 i = d,而不需要顯式的寫(type1)來向編譯器表明類型轉(zhuǎn)換,要做到這點就需要“類型轉(zhuǎn)換操作符”,“類型轉(zhuǎn)換操作符”可以抽象的寫成如下形式:
operator type(){};
只要type是一個類型,包括基本數(shù)據(jù)類型,自己寫的類或者結(jié)構(gòu)體都可以轉(zhuǎn)換。
隱式類型轉(zhuǎn)換運算符是一個特殊的成員函數(shù):operator 關(guān)鍵字,其后跟一個類型符號。你不用定義函數(shù)的返回類型,因為返回類型就是這個函數(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) 對象向基本數(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)對象向不同類的對象的轉(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; }
上面這個程序中X類通過“operator A()”類型轉(zhuǎn)換來實現(xiàn)將X類型對象轉(zhuǎn)換成A類型。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
深入探索C++中stack和queue的底層實現(xiàn)
這篇文章主要介紹了C++中的stack和dequeue的底層實現(xiàn),本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09Pipes實現(xiàn)LeetCode(193.驗證電話號碼)
這篇文章主要介紹了Pipes實現(xiàn)LeetCode(193.驗證電話號碼),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08C++ 十進(jìn)制轉(zhuǎn)換為二進(jìn)制的實例代碼
這篇文章介紹了C++ 十進(jìn)制轉(zhuǎn)換為二進(jìn)制的實例代碼,有需要的朋友可以參考一下2013-10-10編寫C語言程序進(jìn)行進(jìn)制轉(zhuǎn)換的問題實例
這篇文章主要介紹了編寫C語言程序進(jìn)行進(jìn)制轉(zhuǎn)換的問題實例,文中附錄了一個各種進(jìn)制間的轉(zhuǎn)換程序代碼,需要的朋友可以參考下2015-08-08異步http listener 完全并發(fā)處理懲罰http懇求的小例子
異步http listener 完全并發(fā)處理懲罰http懇求的小例子,需要的朋友可以參考一下2013-05-05