C++中operator type函数的使用方法
这期内容当中小编将会给大家带来有关C++中operator type函数的使用方法,以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
在阅读C++标准库的时候,在for_each()章节遇到下面代码,
#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()); //隐式类型转换 MeanValue转化为double std::cout<<"mean calue: "<< mv <<std::endl;}
对于类中的operator double(){},第一次见到这个特别的函数,其实他是"隐式类型转换运算符",用于类型转换用的.
在需要做数据类型转换时,一般显式的写法是:
type1 i;
type2 d;
i = (type1)d; //显式的写类型转,把d从type2类型转为type1类型
这种写法不能做到无缝转换,也就是直接写 i = d,而不需要显式的写(type1)来向编译器表明类型转换,要做到这点就需要“类型转换操作符”,“类型转换操作符”可以抽象的写成如下形式:
operator type(){};
类型转换函数能够实现把一个类 类型 转换成 基本数据类型(int、float、double、char等) 或者 另一个类 类型。其定义形式如下,注意不能有返回值,不能有参数,只能返回要转换的数据类型
只要type是一个类型,包括基本数据类型,自己写的类或者结构体都可以转换。
隐式类型转换运算符是一个特殊的成员函数:operator 关键字,其后跟一个类型符号。你不用定义函数的返回类型,因为返回类型就是这个函数的名字。
1.operator用于类型转换函数:
类型转换函数的特征:
1) 型转换函数定义在源类中;
2) 须由 operator 修饰,函数名称是目标类型名或目标类名;
3) 函数没有参数,没有返回值,但是有return 语句,在return语句中返回目标类型数据或调用目标类的构造函数。
类型转换函数主要有两类:
1) 对象向基本数据类型转换:
#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)对象向不同类的对象的转换:
#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;}
上述就是小编为大家分享的C++中operator type函数的使用方法了,如果您也有类似的疑惑,不妨参照上述方法进行尝试。如果想了解更多相关内容,请关注亿速云行业资讯。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。