zoukankan      html  css  js  c++  java
  • 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类型。

  • 相关阅读:
    Recommended Books for Algo Trading in 2020
    Market Making is simpler than you think!
    Top Crypto Market Makers of 2020
    Top Crypto Market Makers, Rated and Reviewed
    爬取伯乐在线文章(五)itemloader
    爬取伯乐在线文章(四)将爬取结果保存到MySQL
    爬取伯乐在线文章(三)爬取所有页面的文章
    爬取伯乐在线文章(二)通过xpath提取源文件中需要的内容
    爬取伯乐在线文章(一)
    爬虫去重策略
  • 原文地址:https://www.cnblogs.com/Glucklichste/p/11490110.html
Copyright © 2011-2022 走看看