转换操作符
//类类型转换、转换操作符
#include"head.h"
class SmallInt{
public:
SmallInt(int i = 0): val(i){
if(i < 0 || i > 255)
throw std::out_of_range("Bad SmallInt initializer");
}
//期待不合格——id 在输入的末端?~类末端老忘了分号
operator int() const{return val;}//转换符,可以隐式调用
//explicit operator int() const{return val;}//,explicit就不能隐式转换了
//错误的示范
//operator int(SmallInt &); //改正:operator int(void);operator int();
//int operator int(); //改正:{return value;}
//operator int(int = 0); //改正: void
private:
std::size_t val;
};
class Integral{
public:
Integral(int i = 0): val(i){}
operator SmallInt() const {return val % 256;}
private:
std::size_t val;
};
int main(){
/*
SmallInt si(3);
std::cout << si + 3.1415926 << std::endl;//两步自动转换,int,double
std::cout << (int)si + 3.1415926 << std::endl;//即使使用(int),至少也需要一个explicit 的operator int(),不然提示不能从SmallInt转到int
std::cout << si.operator int() + 3.1415926 << std::endl;//注意使用方法:不是si.int()
//test:
double dval;
si >= dval; //si converted to int and then convert to double
if(si); //si converted to int and then cnvert to bool
int calc(int);
int i = calc(si); //si converted to int and call calc
std::cout << si << std::endl;//si convertd t int then call operatr<< on the int value,把explicit加上就看出来了
//测试强制静态转换static_cast<>()
int ival, ival2;
si = 3.541;//和SmallInt si2 = 3.541应该有点区别,这个是纯赋值,那个是初始化
SmallInt si2 = 3.541;//对照组。
ival = static_cast<int>(si) + 3;
ival2 = static_cast<int>(si2) + 3;
std::cout << ival << std::endl;
std::cout << ival << std::endl;
*/
/*只能应用一个类类型转换
int calc(int);
Integral intVal;
SmallInt si(intVal); //ok:convert intVal t int and copy to si
int i = calc(si); //ok:convert si to int and call calc
int j = calc(intVal); //err:no conversion to int from Integral,没有双重自动转换,一次只能掉调用一个,顶多到SmallInt
*/
//前例,标准转换不能在类转换之后使用,但是能在类转换之前使用short提升到int,再利用int版构造函数初始化为SmallInt
void calc(SmallInt);
short sobj;
//sobj promoted from short to int 这是提升
//that int converted to SmallInt through the SmallInt(int) constructor
calc(sobj);
}
pe14_40.cpp
//转换Sales_item
#include"head.h"
class Sales_item{
public:
Sales_item(): isbn("C++ primer"), units_sold(5), revenue(2.0){}
Sales_item&
operator=(const Sales_item &rhs);
operator std::string() {return isbn;}
operator double() {return revenue;}
private:
std::string isbn;
unsigned units_sold;
double revenue;
};
Sales_item&
Sales_item::operator=(const Sales_item &rhs){
isbn = rhs.isbn;
units_sold = rhs.units_sold;
revenue = rhs.revenue;
return *this;
}
int main(){
Sales_item item1;
std::cout << item1 << std::endl;
std::string str = item1;
std::cout << str << std::endl;
}
pe14_41 未解决。。。
class Integral{
public:
Integral(int i): val(i){}
operator const int(){return val++;}//何解?返回的不允许修改?rvalue本来也不让修改啊,不可以当non-const实参传递?也能啊
//operator int() const{return val;}//err:return val++;不允许改变原值(不应该考察这个问题吧。。)
private:
std::size_t val;
};
pe14_42
我返回的bool类型反映的是还书情况
operator CheckoutRecord::bool(){//还书了返回true(还书日期为0当作没还)
if(date_due)
return 1;
return 0;
}
14.43
当然不是唯一含义,当然可以很多种含义,随便定义转换是不恰当的