標籤:ace lin eve ssi 版本 func c++ line const
- Chapter 2
- low-level & top-level const
- constexpr
- type alias
- decltype
- Chapter 3
- Chapter 6 函數
- Chapter 7 類
- 特性
- 可變資料成員
- 返回*this的成員函數
- 基於const的重載
- 委託建構函式
- Chapter 8
- string流
- istringstream
- ostringstream
- Chapter 9
- Chapter 10
Chapter 2low-level & top-level const
int i = 0;int *const p1 = &i; // top-levelconst int c1 = 42; // top-levelconst int *p2 = &ci; // low-levelconst int *const p3 = p2; // low-level (left) & top-level (right)const int &r = ci; // both low-level
constexpr
constexpr int mf = 20;
type alias
typedef double wages; // classictypedef wages base, *p;using SI = Sales_item; // C++11
pointer alias
typedef char *pstring;const pstring cstr = 0; // cstr是指向char的常量指標const pstring *ps; // ps是一個指標,它的對象是指向char的常量指標const char *cstr = 0; // [注意]與 const pstring cstr 不同!
decltype
decltype(f()) sum = x;
decltype 與 引用
decltype(i) e; // 正確decltype((i)) d; // 錯誤, d 是 int&
Chapter 3多維陣列的類型別名
using int_array = int[4];typedef int int_array[4];
Chapter 6 函式宣告一個返回數組指標的函數
int (*func(int i))[10];auto func(int i) -> int(*)[10]; // lamabda
函數重載const_cast
const string &shorterString(const string&, const string &);// 使用const_cast重載原函數的非常量版本string &shorterString(string &s1, string &s2){ auto &r = shorterString( const_cast<const string&>(s1), const_cast<const string&>(s2)); return const_cast<string&>(r);}
函數實參預設實參
typedef string::size_type sz;string screen(sz, sz, char = ' ');string screen(sz, sz, char = '*'); // 錯誤string screen(sz = 24, sz = 80, char); // 正確
預設實參初始值
sz wd = 80;char def = ' ';sz ht();string screen(sz = ht(), sz = wd, char = def);string window = screen(); // 調用 screen(ht(), 80, ' ');
Chapter 7 類特性可變資料成員
關鍵字 mutable
返回*this的成員函數
返回*this表示將對象作為左值返回,意味著可以將一系列操作串連在一條運算式中
myScreen.move(4, 0).set('#');
基於const的重載
class Screen {public: Screen &display(std::ostream &os) { do_display(os); return *this; } const Screen &display(std::ostream &os) const { do_display(os); return *this; }}Screen myScreen(5, 3);const Screen blank(5, 3);myScreen.set('#').display(cout); // 非常量版本blank.display(cout); // 常量版本
委託建構函式
一個委託建構函式使用它所屬類的其他建構函式執行它自己的初始化過程
Chapter 8string流istringstream
istringstream record(line);record >> info.name;
ostringstream
ostringstream formatted;formatted << anyString << endl;cout << formatted.str();
Chapter 9容器操作emplace
以下等價
c.emplace_back(args);c.push_back(T(args));
適配器
stack<int, vector<int>>stk; // 使用vector構造stack適配器
Chapter 10泛型演算法
back_inserter插入迭代器
for_each
lambda 運算式
C++ primer 筆記