C++primer读书笔记9-转换与类类型

来源:互联网 发布:淘宝5皇冠值多少钱 编辑:程序博客网 时间:2024/05/16 07:31
有时候指定了自己类类型来表示某种类型数据如SmallInt,那么为了方便计算就会指定一个转换操作符,将该类类型在某种情况下自动的转换为指定的类型
<1>转换操作符
operator type();
转换函数必须是类成员函数,不能指定返回类型,并且形参列表必须为空,并且通常不应该改变转换对象,所以操作符通常定义为const成员。
#include <iostream>using namespace std;class SmallInt{public:SmallInt(int i=0):val(i){ if(i<0 || i>255) throw std::out_of_range("Bad SmallInt initializer");}~SmallInt(void){};operator int()const{std::cout<<"Translate SmallInt to Int"<<endl;return val;}private:size_t val;};

<2>2级转换
我们在SmallInt中指定的转换是int,但是SmallInt可以间接的转换为其他标准类型如double,float等
SmallInt sm;double dv;sm >= dv//sm convet to int and then convert to doubleif(sm)//sm convet to int and then convert to boolint x = static_cast<int>(si) + 2;// instruct compiler SmallInt to int
<3>禁止转换
假设还有一个类Integral,它可以转换为SmallInt,但是它不能发生2级变换从Integral转换成SmallInt然后再转换成int类型。
int cal(int);Integral intVal;cal(intVal);//error,no convertion to int from Integral

总之:
SmallInt ->standard type ->standard type//okstandard type ->standard type->SmallInt//okIntegral->SmallInt->Int//error
在转换中只能用到一个类类型转换(类类型<->标准类型,类类型<->类类型
<4>不要在一个类中指定多个类类型转换
这样可能会引起在一些转换时候的二义性。
class SmallInt{public:SmallInt(int i=0):val(i){ if(i<0 || i>255) throw std::out_of_range("Bad SmallInt initializer");}SmallInt(double db):val(db){}~SmallInt(void){};operator int()const{std::cout<<"Translate SmallInt to Int"<<endl;return val;}operator double()const{std::cout<<"Translate SmallInt to double"<<endl;return val;}private:size_t val;};void fpComputer(float){}SmallInt sm(100);fpComputer(sm) //error 

<5>构造函数转换二义性
void manip(const SmallInt&);double d;int i;float f;mamip(d);//ok,use SmallInt(double) to convert manip(i);//ok,use SmallInt(int) to convertmanip(f);//error,ambiguous

<6> 构造函数转换和类类型转换同时存在时候的二义性
class Integral;class SmallInt{public:SmallInt(Integral);//...};class Intergal{public:operator SmallInt()const;//...}void compute(SmallInt);Integral intVal;compute(intVal);//error:ambiguous
这里的Integral类型的变量intVal可以通过构造函数以及类类型转换两种方式转换成SmallInt,所以具有二义性
,具体的解决方法是通过显式方式调用如下所示:
compute(intVal.operator SmallInt());compute(SmallInt(intVal));


0 0
原创粉丝点击