学習ノート: C++ を学ぶ 21 日間の第 1 章から第 14 章のハイライト
ポインタの宣言と削除
Type* Pointer = new Type;
delete Pointer;
Type* Pointer = new Type[numElements];
delete[] Pointer;
bad_alloc を処理したくない場合は、メモリ割り当てが失敗したときに NULL を返す new(nothrow) を使用できます。
コピーできないクラス
class President
{
private:
President(const President&);
President& opreator= (const President&);
}
シングルトンクラス
Class President
{
private:
President(){};
President(const President&);
const President& operator=(const President&);
string name;
public:
static President& GetInstance()
{
static President onlyInstance;
return onlyInstance;
}
}
暗黙的な変換を避けるために明示的に使用する
コミュニティ
union UnionName
{
Type1 member1;
Type2 member2;
...
TypeN memberN;
};
virtual、override は仮想関数がオーバーライドされることを保証、final は仮想関数のオーバーライドを禁止、継承を禁止
単項接頭辞増分演算子
Date& operator++()
{
// operator implementation code
return *this;
}
後置インクリメント演算子
Data operator++(int)
{
Data copy(*this);
// increment implementation code
return copy;
}
変換演算子
operator const char*()
{
ostringstream formattedDate;
cout << “Holiday is on: ” << holiday << endl;
dateInString = formattedData.str();
return dataInString.c_str();
}
スマートポインターstd::unique_prt
移動コンストラクターと移動アサイナー
class Sample
{
private:
Type* ptrResource;
public:
Sample(Sample&& moveSource)
{
ptrResource = moveSource.ptrResource;
moveSource.ptrResource = NULL;
}
Sample operator=(Sample&& moveSource)
{
if(this !=&moveSource)
{
delete[] ptrSource;
ptrResource = moveSource.ptrResource;
moveSource.ptrResource = NULL;
}
}
Sample();
Sample(const Sample& copySource);
Sample& operator= (const Sample& copySource);
}
ユーザー定義リテラル
ReturnType operator “” YourLiteral(ValueType value) {// conversion code here}
C++ 型変換演算子
static_cast
dynamic_cast // runtime type identification
reinterpret_cast
const_cast
文法:destination_type result = cast_operator<destination_type>(object_to_cast);
#define を使用して定数を定義します#define identifier value
マクロを使用して複数回インクルードされることを避ける
#ifndef HEADER_H_
#define HEADER_H_
...
#endif
アサートを使用して式を検証するassert(expression that evaluates to true or false);
テンプレート関数: テンプレート関数を呼び出すにはテンプレート パラメーターの型を指定する必要はありませんが、テンプレート クラスを使用する場合はこれが必要です。
template <typename T1, typename T2 = T1>
bool TemplateFunction(const T1& params1, const T2& params2);
テンプレート クラスの静的メンバーの場合、一般的な初期化構文は次のとおりです。
template<typename T> StaticType ClassName<T>::StaticVarName;
パラメーター可変長テンプレート (C++14)
template <typename Res, typename First, typename... Rest>
void Sum(Res& result, First val1, Rest... valN)
{
result = result + val1;
return Sum(result, valN ...);
}
static_assert を使用してコンパイル時チェックを実行する
static_assert(expression being validated, “Error message when check fails”);