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(){};

只要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;
}

 

上面这个程序中X类通过“operator A()”类型转换来实现将X类型对象转换成A类型。

 

原文链接: https://www.cnblogs.com/Glucklichste/p/11490110.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++类的隐式类型转换运算符operator type()

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/302355

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午11:16
下一篇 2023年2月15日 下午11:18

相关推荐