2021年5月20日 星期四

讀書心得 - C++ Primer (5th Edition) - Chapter 4 (2) - Type Conversions

Type Conversions

  • Implicit Conversions
    型別轉換,大部分轉換都是看是否能轉換成 int,例如 char, bool, 和 short。
        bool      flag;   char           cval;
        short     sval;   unsigned short usval;
        int       ival;   unsigned int   uival;
        long      lval;   unsigned long  ulval;
        float     fval;   double         dval;
        3.14159L + 'a'; //  'a' promoted to int, then that int converted to long double
        dval + ival;    //  ival converted to double
        dval + fval;    //  fval converted to double
        ival = dval;    //  dval converted (by truncation) to int
        flag = dval;    //  if dval is 0, then flag is false, otherwise true
        cval + fval;    //  cval promoted to int, then that int converted to float
        sval + cval;    //  sval and cval promoted to int
        cval + lval;    //  cval converted to long
        ival + ulval;   //  ival converted to unsigned long
        usval + ival;   //  promotion depends on the size of unsigned short and int
        uival + lval;   //  conversion depends on the size of unsigned int and long
    
  • Explicit Conversions
    用於我們想明確地強制將 object 轉換為其他類型。cast-name\(expression)。(const相關文章1, const相關文章2)
        // static_cast 最常用的 cast-name
        // cast used to force floating-point division
        double slope = static_cast<double>(j) / i;
    
        // const_cast 用來改變 low-level const (point to const)
        const char *pc;
        char *p = const_cast<char*>(pc); // ok: but writing through p is undefinedc
    
        // reinterpret_cast 對其 operand 進行 low-level bit 的重新解釋
        // 要很理解其型別的 bit 組成才會使用
        int *ip;
        char *pc = reinterpret_cast<char*>(ip);
    
cast 基本上就是擾亂型別,建議能不使用就不使用。

Related Posts:

  • C 語言 - 編譯多個含有 main function 的 C code 編譯多個含有 main function 的 C code     理論上是不行,GCC 無法自行繞過某某函式去編譯,通常是給條件去讓編譯器來達到 "只有一個你想要的 main function" 編譯目的。有人會問為什麼會有多個 main function,我想多半是因為想 Debug。 1. 利用 #ifdef other.c #ifdef DEBUG int main () { … Read More
  • BCB OLE操作EXCEL(1) BCB 操作 EXCEL、WORD ( OLE的應用 ) 之前有講工作關係需要彙整報告,報告不外乎 WORD、EXCEL、PDF檔 程式要操作 WORD、EXCEL 可以靠微軟的 COM(Component Object Model)或 .NET Framework. 照理說應該要用 .NET Framework ( 比較潮?? ) 但是公司前輩使用的是 COM 新人啥都不懂乖乖跟著學就對了,其實也不知道兩者實際差異 因為從來沒試過另外一種… Read More
  • C 語言 - #ifndef #ifndef 用途 在 .h 檔確保只會被編譯一次 #ifndef HELLO_H // 有些人會定義成 _HELLO_H_ #define HELLO_H // 但目的就是不會被重複編譯 #include <stdlib.h> int helloIntro(char** str); int main() __attribute__((weak)); #endif … Read More
  • C 語言 - size_t 及各個常見類型 typedef unsigned int size_t // 通常定義在 stddef.h int8 : -128 ~ 127 int16 : -32768 ~ 32767 int32 : -2147483648 ~ 2147483647 int64 : -9223372036854775808 ~ 9223372036854775807 uint8 : … Read More
  • Python bin() Python bin() bin(10) // 0b1010 type(bin(10)) // <class 'str'> bin(10)[2:] // 1010 … Read More

0 意見:

張貼留言

Popular Posts