物探论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1097|回复: 0

[Envi] C++库研究笔记——操作符重载实现类型转换&这样做的...

[复制链接]
发表于 2013-8-12 11:29:49 | 显示全部楼层 |阅读模式
目标:已知这个接口:[cpp] view plaincopystd::vector<double> add_vec(double *d1, double *d2)  {  .....  return result;  }  
我们自定义了这个类:[cpp] view plaincopy<span style="font-size:14px;">class array  {  int size_;  double *data_;  ....  };</span>  
要求实现:[cpp] view plaincopyarray v1(10), v2(10);  add_vec(v1, v2);  
留意到,当array 类型传入add_vec时,会遇到(double*) 类型的“试探性”强制转换, 所以,我们只要做一个从array到,(double*)的类型转换即可。
这样做的好处:1.有了类型转换,我们不需要再写这样一个多态函数实现array 与array的相加[cpp] view plaincopy<span style="font-size:14px;">std::vector<double> add_vec(array d1, array d2)  {  .....  return result;  }  </span>  
2.以下的接口:[cpp] view plaincopy<span style="font-size:14px;">std::vector<double> add_vec(double* d1, double* d2)</span>  可能重写起来非常麻烦,甚至add_vec(double*, double*) 是别人封装好的,我们看不到源代码,此时更谈不上重写

实现方法及测试代码:(直接在这个代码上增加,所以代码有些乱)C++类型转换操作符(type conversion operator)
[cpp] view plaincopy<span style="font-size:14px;">#include <iostream>     class D {   public:      D(double d) : d_(d) {          data_=new double[10];          for(int i=0; i<10; i++)              data_=d;      }        ~D()    {   delete []data_;   }        /* “(int)D”类型转换 */      operator int() const {          std::cout << "(int)d called!" << std::endl;          return static_cast<int>(d_);      }        // for: double me=    *d1;      //ok      double& operator*(void) {          return *data_;      }        // for: double *me2= (double*)d1;      operator double*(void){          return data_;      }       private:      double d_;      double *data_;  };     int add(int a, int b) {      return a + b;  }    #include <vector>  std::vector<double> add_vec(double* d1, double* d2)  {      std::vector<double> r(10);      for(int i=0; i<10; i++){          r=d1+d2;      }                return r;  }       int main() {      D d1 = 1.1;      D d2 = 2.2;      std::cout << add(d1, d2) << std::endl;        double me=    *d1;      //ok      std::cout<<"me:"<<me<<std::endl;      double *me2= (double*)d1;   // ok        std::vector<double> r;      r=add_vec(d1, d2);      for(int i=0; i<r.size(); i++){          std::cout<<r<<" "<<std::endl;      }          //std::cout << add_vec(d1, d2) << std::endl;        return 0;  }</span>  
输出:(int)d called!(int)d called!3me:1.13.3 3.3 3.3 3.3 3.3 3.3 3.3 3.3 3.3 3.3

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|物探论坛 ( 鄂ICP备12002012号 微信号:iwutan )

GMT+8, 2024-3-29 07:04 , Processed in 0.070252 second(s), 15 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表