Implicit Conversions

  • Type conversions happen automatically when we use an object of one type where an object of another type is expected.
  • if can, the small type operands are generally promoted to a lager type. (preseve precision)

Other Implicit Conversions

Explicit Conversions

虽然有时候是必要的,但是casts还是内在危险的

Named Casts

static_cast

就是一般的转换,包括int2float,void 和指针间的转换

当是指针之间的转换时,这个cast确保了指针的值是被保留的,但是如果没有匹配的时候用是undefined:

double d = 0.28976;  
void *p = &d;  
cout << *(static_cast<double*>(p));    // 0.28976

Use for Explicit Class-Type Conversions

item.combine(static_cast<Sales_data>(cin));

const_cast

Changes only a ==low-level const== in its operand. (也就是说,只能用在pointer和reference上) “casts away the const”

⚠️ if the original object is nonconst, then we casts away the const and obtain write access is legal. However, if the underlain is originally a const, the access is undefined.

static_cast 职能不互通

🔗const_cast and Overloading