- ASCII
可以說是最古老的信息交換標準,它主要用於顯示美國和其他西歐語言。
- Unicode
Unicode 是一種統一碼,它能夠表示各種不同的語言,例如 ASCII 是 Unicode 的子集。
- 實際意義
C++ 標準允許實現提供擴展源字符集和擴展執行字符集,例如下面的代碼:
cout << "You is \u0067ood person." << endl;
如果無誤,這將輸出 "You is good person." 字符串。
- signed char 和 unsigned char
char 在默認情況下不是沒有符號,也不是有符號。是否有符號由 C++ 實現決定。這樣做的好處是開發人員可以最大限度地將這種類型和硬件屬性匹配起來。
char fodo;
unsigned char bar;
signed char snark;
如果將 char 用作數值類型,則 signed char 與 unsigned char 之間的差異非常重要。unsigned char 類型的表示範圍通常爲 0 ~ 255,signed char 類型的表示範圍通常爲 -128 ~ 127。例如要使一個 char 類型能表示 200 這樣大的數,則在某些系統上可以,但在某些系統上又不行。另一方面如果使用 char 來存儲 ASCII 字符,則 char 有沒有符號都沒關係,因爲標準 ASCII 的範圍爲 0 ~ 127。
- wchar_t
程序需要處理的字符集可能無法用一個 8 位字節表示,如中日文系統。這種情況下,大多使用 wchar_t 比較方便表示。
wchar_t bob = L'P';
wcout << L"tall" << endl;
- char16_t 和 char32_t
隨着編程人員日益熟悉 Unicode,wchar_t 顯然是不夠用的,這時候就出現了 char16_t 和 char32_t 類型。它們都是無符號的,前者 16 位,後者 32 位。
char16_t ch1 = u'q';
char32_t ch2 = U'\U0000222B';
- bool 類型
布爾變量可以是 true 或 false,它代表了 1 和 0,在實際開發中很常見。例如下面的代碼:
struct Role {
bool is_live;
int blood;
} role;
我們可以用 is_live 來表示一個角色的生與死,即 1 或 0 。
- 隱式的運算規則
cout << 9 / 5 << endl; -> 1
cout << 9L / 5L << endl; -> 1
cout << 1.e7 / 9.0 << endl; -> 1111111.111111
cout << 1.e7f / 9.0 << endl; -> 1111111.111111
cout << 1.e7f / 9.0f << endl; -> 1111111.125000
在 C++ 中對於 int 類型與 int 類型的運算,結果還爲 int 類型。double 類型與 float 類型的運算,結果爲 double 類型。double 類型與 double 類型的運算結果爲 double 類型。而如果常量浮點未顯示的標明類型,則爲 double 類型。
- 數值轉換的潛在問題
在很多時候,數值轉換可能會帶來一些麻煩,你可能想讓程序運算的精度降低來提高效率,但有時候卻會結果卻會出乎意料。比較典型的例子就是將 double 類型轉換爲 float 類型,這個轉換的過程叫做截斷,它的精度會降低,在某些情況下,結果是不確定的,甚至是無窮值。
double lbs = 1e127;
float test = lbs;
cout << lbs << endl; -> 1e127
cout << test << endl; -> inf (無窮大)
- 初始化方式進行的轉換(C++11)
int tree = 4.E20 // ? value
int lbs(2.5); // double convert to int
const int code = 66;
char c1 {code};
char c2 = {code};
char c3 = {256};
- 表達式中的轉換
在計算表達式時,C++將 bool、char、unsigned char、signed char 和 short 數值轉換爲 int。因爲 int 是計算機中最自然的類型,這意味着計算機使用這種類型時,運算速度可能最快。
short chickens = 20;
short ducks = 35;
short fowl = chickens + ducks;
也就是說 chickens 和 ducks 變量首先被轉成 int 類型,再將運算的結果轉換爲 short 類型傳給 fowl 變量。
還有一些其他的提升,如 short 類型比 int 短,則 short 被轉換爲 int。同樣 wchar_t 被提升爲 int、unsigned int、long 或 unsinged long 類型。
- 強制類型轉換
(int)lbs // old C
int(lbs) // new C++
static_cast<int>(lbs) // new C++
本質上 type (value) 與 static_cast <type> (value) 沒有區別,但 static_cast <type> (value) 的轉換方式比 type (value) 方式更加嚴格。