1. 程式人生 > >C++ Primer 總結之Chap2 Variables and basic types

C++ Primer 總結之Chap2 Variables and basic types

本章包含知識點:
1. 常用型別大小及基本規律
2. 常量表達式
3. constextern關鍵字
4. 標頭檔案相關

  1. integeral types(整值型別 指int, char, bool,而整型特指int

    • define sizeof(machine word) = W
    • 1 byte = 8 bits
    • 1 word = 4 bytes(typically)
    • 2^16=32768 , 2^32=2147483648

    • (at least)實際上只規定了最小值,並無嚴格規定

      type
    size(byte)
    char 1
    wchar_t 2
    size_t 4
    short 2 or W/2
    int 4(2 at least) or W
    long 4 on 32 and 8 on 64
    float 4
    double 8
    long long 8
    long double 8
  2. 注意,if(s<0)s=-s;不一定都能取到s的絕對值——當s是個有符號數且為最小值時,-s還是它自己,因為-s已經超出範圍了,按照規則轉換到範圍內之後恰好還是原來的那個最小負數(max positive + 1 = min negative)。另外,這裡的-

    也不是減號,而是一個一元取反操作符。

  3. If the value given to an object is out of its range, then if it’s an unsigned value, it would always be adjusted to be a non-negative number, it gets the remainder of the value modulo the range of that type; if it’s signed value, then usually the same way but not guranteed.

    unsigned
    short k1 = 32768 * 2; short k2 = -32769;//The range is 32678*2,it's 32678*2-32769 cout << k1 << ' ' << k2;//0, 32767
  4. Literal integer constant:

    024;// octal
    0x14;// hexadecimal
    20;// decimal

    Default type is int or long,但可加上字尾強制轉換:

    12u;// unsigned
    12L;// long
    12UL or 12LU;// unsigned long

    【注意!!!】整數字面常量沒有負數!常見的-1其實是一個表示式,取1的相反數,負號是一元取反操作符。-10u其實是4294967286,即10取反後為-10但又被調整到非負範圍內(強制型別轉換髮生在最後)

  5. Floating-point literal constant:
    3.14e5 , 0E0 , .001f,大小寫皆可,預設double,字尾f轉單精度,字尾L轉extended precision(極少用)

    • ‘a’ : char
    • L’a’:wchar_t
    • 字元可用'\ooo''\xddd'八和十六進位制數字表示該字元,如’\115‘(‘M’)
  6. Chracter String Literals

    • an array of const char,可以退化為指向常量字元的指標
    • 自動加終止符(null character)
    • wide string literal字首加L
    • 多個由空格類間隔分隔的字串會自動連線成一個,這樣就可以多行輸出一個長句了,但若連線常字串和寬字串,it’s undefined. Putting a backslash as the last character on a line causes the line and the next to be treated as a single line. Any leading spaces or tabs on the subsequent lines are part of the literal.

      cout<<"This is "
            "a " "Hello "  "world\n";
      cout<<"This is a \
            Hello word\n";//More than one whitespace!
      
  7. Definitely, we should not rely on machine dependent behaviors, such as assume that the size of int is a fixed and known value like 4.

  8. copy-initialization uses the equal(=) symbol, direct-initialization places the initializer in parentheses.

  9. 全域性變數不初始化預設為0,' ',NULL...

    • A definition of a variable allocates storage for the variable and may also initialize it——create it. There must be one and only one definition of a variable in a program.
    • A declaration makes known the type and name of the variable to the program. A definition is also a declaration.
    • Any variable used in more than one file requires declarations that are separate from the variable’s definition.
      extern int i;// declares but does not define i,
                   // with a initializer become definition
      int i;//declares and defines i
           // Can't define a variable twice
  10. scope分為global, local, statement三種,在底層裡可用同名覆蓋上一層,甚至連型別都能改變。In a word, names can be redefined in an inner scope. But this may be confusing so we should also avoid it.

  11. const的意義:

    • readability,從不明意義的常量變為更易讀的變數;
    • maintainability,修改的時候只要在定義處修改即可,方便很多。而且加上const不會被無意中修改掉
    • const變數預設是相對於檔案local,即便你把它寫在全域性位置上。除非定義的時候用extern const int a=8;這樣子,那就相當於可以被其他檔案使用了。non-const variable的話,只要放在檔案的全域性位置上,然後在別的檔案中用extern typeName variableName;即可獲取~
  12. extern是一個關鍵字,它告訴編譯器存在著一個變數或者一個函式,如果在當前編譯語句的前面中沒有找到相應的變數或者函式,也會在當前檔案的後面或者其它檔案中尋找該定義。這裡的變數和函式當然是指各個檔案的全域性變數啦,因為它不可能連函式(包括main函式)內部都尋找的。

  13. 全域性變數重名的話在各個檔案單獨編譯時不出錯,但在將多個檔案連線在一起的時候,這些變數是互相可見的,亦即同名就會collide(這也是header裡宣告的變數必須加extern的原因。設若不加,則若有多個原始檔包含了該標頭檔案,那這變數的定義就出現了兩次了,而且都是在全域性變數的位置上,link的時候就出錯了;另外,這裡的互相可見是在link階段,並不代表可以直接使用其他檔案的全域性變數,因為這樣你壓根過不了自己檔案的編譯,要用別人的全域性變數還是得用extern

    • Reference is only an alias. It must be initialized by an object of the same type when created. And once created, there is no way to rebind it to another object.
    • const reference is a reference that may refer to a const object, which is not possible for a non-const reference. But it can also refer to a non-const object. What’s more, it can be initialized to an rvalue or an object of different but related(即可轉換的) type.(實際上是構建了一個臨時的相應型別的變數讓reference指向該變數,由於read only所以可行)
      int val = 3;
      const int cVal = 4;
      int &a = val;
      int &b = cVal;//error
      const int &c = val;
      const int &d = cVal;
      c = 5;//error
      int &e = 8;//error
      const int &f = 33;//ok
      double dVal = 3.14;
      const int &g = dVal;//ok, because read-only, same as
                          //int temp=dVal;const int &g=temp;
  14. typedef 定義型別的同義詞,如

    typedef double wages;
    wages hourly,weekly;
  15. enum open_mode {input = 2, output, append = 3, other};

    The value assigned to enum should be a constant expression, which can be evaluated by compiler at compile time. enumerator is const. But an enum object is not const.

  16. When we define a class, we start by defining its interface——the operations that the class will provide. From these operations we can then determine what data the class will require to accomplish its tasks and whether it will need to define any functions to support the implementation.

  17. 定義class記得要加分號,報錯的cpp檔案可能是因為它包含的標頭檔案少了分號,記得檢查。

  18. class 成員預設privatestruct成員預設publicclass這個關鍵字還用於定義模板引數,除此之外無差別。

  19. Headers normally contains class definition, extern varibale declaration, function declaration. Two benefits:

    1. Consistency, all files are guaranteed to use the same declaration for a given entity;
    2. Only the header needs to be updated when changes are needed.

    A header should logically belong together because it needs time to compile. And headers are for declarations, not definitions. Definitions should NOT occur in a header. e.g. extern int val = 10; double val;//wrong, both are definitions

    However, there are 3 exceptions when we can use definitions: class, const object whose value is known at compile time, inline functions. (const預設是local的,所以可以。如果初始化用到 constant expression,很多時候不存在記憶體消耗而是直接替換了;如果用函式來初始化的話,那就得把它放到原始檔中防止函式被反覆呼叫了,加上extern也可以共享)

  20. Header guard

    
    #ifndef HEADER_H
    
    
    #define HEADER_H
    
    //blablabla
    
    
    #endif
    

Reference : C++ Primer 4th edition(評註版)

相關推薦

C++ Primer 總結Chap2 Variables and basic types

本章包含知識點: 1. 常用型別大小及基本規律 2. 常量表達式 3. const和extern關鍵字 4. 標頭檔案相關 integeral types(整值型別 指int, char

C++ Primer 總結Chap4 Arrays and Pointers

本系列為本人溫習C++基礎時所記的tips,歡迎各位同學指正,共同進步TvT。 Modern C++ programs should almost always use vector and i

C++Primer第五版 習題答案 第二章 變數和基本型別(variables and basic types

2.1 C++語言規定一個int至少和一個short一樣大,一個long至少和一個int一樣大,一個long long至少和一個long一樣大。每個的最小尺寸分別為:short,16位;int,16位;long,32位;long long,64位。 除去布林

PBRT_V2 總結記錄 Random Variables and Probability Mass Function

參考 : https://www.scratchapixel.com/lessons/mathematics-physics-for-computer-graphics/monte-carlo-methods-mathematical-foundations   Rand

C++面試總結常用基礎知識

轉載自:https://www.jianshu.com/p/e21d99638cf9C++程式設計師面試一般都是以下三板斧1.基礎問答2.然後一頓虛擬函式、虛擬函式表、純虛擬函式、抽象類、解構函式、拷貝建構函式3.運算元過載、STL、智慧指標-------------------分割線------------

C語言總結void使用規則

規則一   1.規則說明。   如果函式沒有返回值,那麼應宣告為void型別。   在C語言中,凡不加返回值型別限定的函式,就會被編譯器作為返回整型值處理。即不加返回值說明的函式為返回為int的函式。         2.示例。 void function() {}

C++ primer 第十二章筆記 動態內存

weak memory ont 創建 tor size prim 自動 pre 動態內存: 運算符:new,delete 智能指針: 頭文件:memory shared_ptr:允許多個指針指向同一個對象; unique_ptr:"獨占"所指向的對象; weak_ptr:

C++ Primer高速入門六:數組和指針

borde ott 1.5 del word ans 12px 關聯 bre 更新:勘誤,delete [] 豬 我們知道,C語言以及早期的面向結構的語言差點兒都支持數組定義。比方整形數組int 女神[2]。表示有倆數: 女神[0], 女神[1]。她們都是

C++ Primer 5th(中文版)》“概覽的概覽”第一部分——C++基礎,第二章

常量 隱藏 默認值 基礎 ons int 整數 構造 基於 C++ Primer已經快讀完了,但這本書光讀一遍是絕對不行的。至少讀兩遍,把大部分可操作的習題做一遍,才能記住大部分細節。在這裏,我想對C++第一部分——C++基礎進行一次非常非常非常簡略但結合核心部分的整合,帶

Qt學習總結C魚)信號與槽01

Qt 學習 總結 C魚 自動關聯 第一種自然是手動關聯了,只要調用connect函數就能實現自動關聯。這裏重點講第二種,自動關聯:為了實現槽函數自動進行關聯,對於Qt窗口部件已經提供的信號,可按照以下規範命名:void on_&lt;窗口部件名稱&gt;_&lt;信號名

Qt學習總結C魚)路徑參數引用

Qt學習總結(C魚)之路徑參數引用1.引用相對路徑: 例如: QCursor cursor(QPixmap("1.png")); 問題:會發現引用失敗,這是因為相對路徑都是從當前工作目錄開始找起文件的。可以通過以下函數獲取當前工作目錄: bool QDir::setCurrent ( co

C++設計模式-工廠模式的總結

ide char* break product 有一個 對象 ride pan 多態 工廠模式分為3種,即簡單工廠模式、工廠方法模式、抽象工廠模式,其實大同小異,總結下來就是: 簡單工廠模式:一個工廠,多個產品。產品需要有一個虛基類。通過傳入參數,生成具體產品對象,並利用

C++ Primer(第五版) 整理和總結

.cn 可能 體系 習題 內置 需要 如果 內存 標準庫 Preface:本博文不記錄C++課後習題答案,而是通過一種提問+解答的方式對每章的內容進行梳理,用於自我回顧和總結,真正做到將所讀的知識變成自己的東西 在這裏引用孟巖老師的一段話(來源於https://blog.c

C++ primer 個人學習總結

歡迎大家來訪二笙的小房子,一同學習分享生活! 文章目錄 1. 個人見解:C++ 2. primer學習總結 2.1 第一章:開始 2.2 Part1:C++基礎 2.3 Part2:C++標準庫 2.4 Part3:類設

C Primer Plus--高階資料結構二叉樹

目錄 二叉搜尋樹 Binary Search Tree 用C構建二叉樹ADT 樹結構的定義 C Primer Plus--高階資料結構表示之二叉樹 二叉搜尋樹 Binary Search Tree 二叉樹是一種高階資料結構。樹中的每個節點都包含一個專案和兩個指向其他

C Primer Plus--高級數據結構二叉樹

com 指向 can roo sca 表示 continue plus 可能性 目錄 二叉搜索樹 Binary Search Tree 用C構建二叉樹ADT 樹結構的定義 C Primer Plus--高級數據結構表示之二叉樹 二叉搜索樹 Binary Search

C++ Primer Plus書--C++指標及使用new分配記憶體,使用delete釋放記憶體

先來個簡單的程式初步認識一下指標  #include "iostream" using namespace std; int main() { // 定義一個int型變數 int num = 123; // 定義一個int型指標變數 int * p_num; // 指標指向

C++ Primer Plus書--C++字串

首先類似c語言裡的字串: // 陣列長度11實際上已經把字串結尾的\0字元考慮進去了 char bird[11] = "Mr. Cheeps"; // 讓編譯器自己判斷字串的長度 char fish[] = "Bubbles"; 假如有如下程式碼: char boss[8] = "Boz

C++ primer Plus書---C++陣列

先看下面的程式碼 #include "iostream" using namespace std; int main() { int cards[4] = {1, 2, 3, 4}; int hand[4]; hand[4] = {2, 3, 4, 5}; hand = cards;

C++ Primer 第五版 第一章總結

   由於第一章只是簡單介紹,我就沒什麼好總結的。於是,我就寫一些我覺得自己要記住和自己以前不知道的知識點吧。    1. iostream庫包含兩個基礎型別 istream 和 ostream,分別表示輸入流和輸出流。一個流就是一個字元序列,是從IO裝置