プログラム班? CからC++へ †個人的なC++のメモ書き。 需要はゼロな気がしますけど。 iostream †iostreamはC++の標準的な入出力ライブラリで、C言語のstdio.hにあたるものです。 利点 †
例 †とりあえずC版のコードから。 #include <stdio.h> int main() { char c; int i; float f; printf("c = "); scanf("%c", &c); printf("i = "); scanf("%d", &i); printf("f = "); scanf("%f", &f); printf("入力された値は\n"); printf("c = %c\n", c); printf("i = %d\n", i); printf("f = %f\n", f); printf("です。\n"); return 0; } C++版。 #include <iostream> using namespace std; int main() { char c; int i; float f; cout << "c = "; cin >> c; cout << "i = "; cin >> i; cout << "f = "; cin >> f; cout << "入力された値は" << endl; cout << "c = " << c << endl; cout << "i = " << i << endl; cout << "f = " << f << endl; cout << "です。" << endl; return 0; } 解説 †
多重配列の動的確保 †大きさが実行時まで未定の二次元以上の配列を利用する方法。 newを用いる方法は解放が面倒です。 newを用いる †例としてint型の配列をnew演算子を用いて作成します。 widthとheightに二つの次元の配列の大きさが代入されているものとします。 int main() { int width = 5; int height = 10; //配列の確保 int** array1 = new int*[width]; for(int i = 0; i < width; ++i) { array1[i] = new int[height]; } //処理 Some(); //解放 for(int i = 0; i < width; ++i) { delete[] array1[i]; } delete[] array1; } vectorを用いる †int main() { int width = 5; int height = 10; //配列の確保 std::vector< std::vector<int> > array1(width); for(int i = 0; i < width; ++i) { array1[i].resize(height); } //処理 Some(); boost::multi_arrayを用いる †int main() { int width = 5; int height = 10; //配列の確保 boost::multi_array<int, 2> array1(boost::extents[width][height]); //処理 Some(); 配列や構造体のゼロ初期化 †POD(Plain Old Data)に限ります。 int array[10] = {}; struct some_type{int INT; char CHAR; double DOUBLE;} v = {}; memsetするのとどっちがいいのだろうか。 C++形式のキャスト †C++ではC形式のキャストは非推奨となり、新たに四種類のキャストが加えられています。 static_cast<T> †暗黙の変換、またはその逆変換。基本的にこのキャストを使う。 dynamic_cast<T> †ベースクラスを指すポインタから派生クラスを指すポインタを安全に得ることができる。ただしベースクラスが仮想関数を持つことが必要。 reinterpret_cast<T> †どんな型へもキャストできる。実装依存。 const_cast<T> †constやvolatileを取り除く。 Technical Report 1 †C++の新しい拡張機能。
例 †以下shared_ptrの利用例。ポインタがスコープから外れて破棄されるときに、ポインタの中身に対してもdeleteが呼ばれる。 #include <iostream> #include <memory> class Destructable { public: Destructable(){} ~Destructable() { std::cout << "Object is Destructed." << std::endl; } }; int main() { std::tr1::shared_ptr<Destructable> smart_ptr(new Destructable()); return 0; } C++で2進数値を記述 †templateを利用してリテラルとして2進数値を記述する方法。面白い。 開発環境 †Eclipse - CDT †C++/CLI †Visual Studioの設定 †プロジェクトのプロパティから共通言語ランタイムのサポートをするように変更。 参照設定を追加する。 C++0x †VS2010で自動型推論とかが使えるらしい. |