#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; };
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>禁止转换
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在转换中只能用到一个类类型转换(类类型<->标准类型,类类型<->类类型
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
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
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));
C++primer读书笔记9转换与类类型,布布扣,bubuko.com
原文地址:http://blog.csdn.net/ddupd/article/details/38001773