プログラム班?
個人的なC++のメモ書き。
需要はゼロな気がしますけど。
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を用いる方法は解放が面倒です。
例として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; }
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();
POD(Plain Old Data)に限ります。
int array[10] = {}; struct some_type{int INT; char CHAR; double DOUBLE;} v = {};
memsetするのとどっちがいいのだろうか。
C++ではC形式のキャストは非推奨となり、新たに四種類のキャストが加えられています。
暗黙の変換、またはその逆変換。基本的にこのキャストを使う。
ベースクラスを指すポインタから派生クラスを指すポインタを安全に得ることができる。ただしベースクラスが仮想関数を持つことが必要。
どんな型へもキャストできる。実装依存。
constやvolatileを取り除く。
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; }
templateを利用してリテラルとして2進数値を記述する方法。面白い。
プロジェクトのプロパティから共通言語ランタイムのサポートをするように変更。 参照設定を追加する。
VS2010で自動型推論とかが使えるらしい.