Type Conversion/Casting Confusion in C++ -


can explain me, type conversion , type casting? when should use each of them? i'm sorry if obvious question, i'm new , come ruby background , i'm used "to_s" , "to_i" , like! in advance, ell

conversion when value is, um, converted different type. result value of target type, , there rules output value results input (of source type).

for example:

int = 3; unsigned int j; j = i; // value of "i" converted "unsigned int". 

the result unsigned int value equal i modulo uint_max+1, , rule part of language. so, in case value (in english) still "3", it's unsigned int value of 3, subtly different signed int value of 3.

note conversion happened automatically, used signed int value in position unsigned int value required, , language defines means without saying we're converting. that's called "implicit conversion".

"casting" explicit conversion.

for example:

unsigned int k = (unsigned int)i; long l = long(i); unsigned int m = static_cast<unsigned int>(i); 

are casts. specifically, according 5.4/2 of standard, k uses cast-expression, , according 5.2.3/1, l uses equivalent thing (except i've used different type). m uses "type conversion operator" (static_cast), other parts of standard refer "casts" too.

user-defined types can define "conversion functions" provide specific rules converting type type, , single-arg constructors used in conversions too:

struct foo {     int a;     foo(int b) : a(b) {}                   // single-arg constructor     foo(int b, int c) : a(b+c) {}          // two-arg constructor     operator float () { return float(a); } // conversion function };  foo f(3,4);              // two-arg constructor f = static_cast<foo>(4); // conversion: single-arg constructor called float g = f;             // conversion: conversion function called 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -