What is the difference between type casting and type conversion in C++ or Java?

后端 未结 8 1614
Happy的楠姐
Happy的楠姐 2020-12-13 20:15

What is the difference between typecasting and typeconversion in C++ or Java ?

8条回答
  •  庸人自扰
    2020-12-13 21:10

    According to the Wikipedia article:

    "In the C family of languages, the word cast typically refers to an explicit type conversion (as opposed to an implicit conversion), regardless of whether this is a re-interpretaion of a bit-pattern or a real conversion."

    Here is a C++ example:

    double d = 42.0;
    int i = d; // Here you have an implicit conversion from double to int
    int j = static_cast(d); // Here you have a cast (explicit conversion).
    

    Here is a Java example (note that in Java unlike C++ you can't implicitly convert from double to int):

    int i = 42;
    double d = i; // Here you have an implicit conversion from int to double
    int j = (int)d; // Here you have a cast (explicit conversion).
    

提交回复
热议问题