目标:已知这个接口:[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
|