初學者在剛開始讀 C++ Primer 的時候,總是容易被書中各種初始化搞得頭大:默認初始化、串列初始化、值初始化、類內初始值、建構式初始值串列、new int 和 new int() 的區別...
本文把書中這些概念集中總結如下,大括號【】內為原書中文版第 5 版的相應頁碼,
-
串列初始化(list initialization)【P39】:用花括號
{}來初始化變數,在 C++11 中得到全面應用-
// 以下 4 種初始化的形式都可以 int i = 0; int i = {0}; int i{0}; int i(0); long double ld = 3.1415; int a{ld}; // 報錯,轉換存在資訊丟失的風險 int b = {ld}; // 報錯,轉換存在資訊丟失的風險 int c(ld); // 正確,但資訊丟失 int d = ld; // 正確,但資訊丟失 -
如果串列初始化存在資訊丟失的風險, 編譯器將報錯,
-
-
默認初始化【P40】:如果定義變數時沒有指定初始值,則變數被默認初始化
- 型別別:由類負責初始化
- 內置型別
- 定義在任何函式體之外(可以在命名空間中):初始化為 0
- 定義在函式體內部(包括定義在類內的類成員【P236】)的非靜態變數:未初始化!
- 區域靜態變數【P185】:如果沒有顯式的初始值,將執行值初始化,內置型別將初始化為 0
-
值初始化(value initialization)【P88、P118】
- 何時進行值初始化?
- 只提供容器(陣列除外?)的元素數量而不指定初值時,就會執行值初始化
- 內置型別區域靜態變數
- new 型別,后面帶圓括號,如:
new int(),new string()【P408】
- 內置型別:初始值設為 0
- 型別別:由類的默認建構式初始化
- 何時進行值初始化?
-
類的物件無論在函式內/外,全域/區域,靜態/非靜態,其初始化都是由類負責
- 類內初始值【P65】
- 建構式初始值串列【P238】
-
類內初始值(in-class initializer)【P65】
-
C++11 新標準,在類的定義中直接指定初值,可以用等號或者花括號,但是不能用圓括號,
-
class SalesData { std::string bookNo; unsigned unitsSold = 0; double revenue {0.0}; }; -
【P238】推薦使用類內初始值!
-
-
建構式初始值串列【P238】:用建構式的引數初始化成員變數,
-
class SalesData { public: SalesData(const std::string &s) : bookNo(s) {} SalesData(const std::string &s, unsigned n, double p) : bookNo(s), unitsSold(n), revenue(p*n) {} };
-
-
new【P408】
-
string *ps1 = new string; // 默認初始化為空 string string *ps2 = new string(); // 值初始化為空 string int *pi1 = new int; // 默認初始化,*pi1 值未定義! int *pi2 = new int(); // 值初始化,*pi2 為 0 const int *pci - new const int(1024); // 分配并初始化一個 const int
-
原文地址:https://www.cnblogs.com/tengzijian/p/15376463.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/306137.html
標籤:其他
上一篇:淺析 Java 記憶體模型
