zoukankan      html  css  js  c++  java
  • C++primer读书笔记9-转换和类类型

    有时指定自己的类类型来表示某些类型的数据,如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 double
    if(sm)		//sm convet to int and then convert to bool
    int 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	//ok
    standard type ->standard type->SmallInt		//ok
    Integral->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 convert
    manip(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));


    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    import,from,as
    推荐书籍
    谈谈数字货币,即代币,存在于网络世界中的货币
    KVM虚拟机平台
    系统运维总结第9章
    系统运维总结第8章
    渗透测试的一些工具和平台
    该死的字符集!!!
    当U盘装系统失败后空间变小,使用Windows的diskpart工具重新分区
    kali linux更新源
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4853764.html
Copyright © 2011-2022 走看看