可以从派生类类型到基本类类型引用的转换,却没有基类到派生类类型引用的转换。编译器不会将派生类对象转换为基类对象转换为基类对象。引用转换不同于转换对象。
Item_base item; //object of base type
Bulk_item bulk; //object of derived type
//ok:uses Item_base::Item_base(const Item_base &)
Item_base item(bulk); //bulk is "sliced down" to its Item_base porition
//ok:calls Itme_base::operator=(const Item_base &)
item_base=bkk; //bulk is "sliced down" to its Item_base porition
基类到派生类的自动转换不存在
Item_base base;
Bulk_item *bulk_p=&base; //error
Bulk_item &bulk_ref=base; //error
Bulk_item bulk=base; //error
基类指针或引用实际绑定到派生类对象时,从基类到派生类的转换也存在限制
Bulk_item bulk;
Item_base *item_p=&bulk; //OK,dynamictype is Bulk_base
Bulk_item *bulk_p=item_p; //error:can't convert base to derived
可以用Bulk_item *bulk_p=static_cast<Bulk_item *>(item);
Item_base item; //object of base type
Bulk_item bulk; //object of derived type
//ok:uses Item_base::Item_base(const Item_base &)
Item_base item(bulk); //bulk is "sliced down" to its Item_base porition
//ok:calls Itme_base::operator=(const Item_base &)
item_base=bkk; //bulk is "sliced down" to its Item_base porition
基类到派生类的自动转换不存在
Item_base base;
Bulk_item *bulk_p=&base; //error
Bulk_item &bulk_ref=base; //error
Bulk_item bulk=base; //error
基类指针或引用实际绑定到派生类对象时,从基类到派生类的转换也存在限制
Bulk_item bulk;
Item_base *item_p=&bulk; //OK,dynamictype is Bulk_base
Bulk_item *bulk_p=item_p; //error:can't convert base to derived
可以用Bulk_item *bulk_p=static_cast<Bulk_item *>(item);