以下のような、profクラスの配列を作成しようとすると、メモリを静的に割り当てることになり領域を使いすぎてしまいます。
そこで、動的にメモリ割り当てを行うために、new演算子を用いてオブジェクト生成を行います。
演算子newは、変数を格納する領域を割り当てて、ポインタを返します。
#include <iostream>
int main() {
class prof {
public:
std::string name;
std::string address;
std::string tel;
int age;
float weight;
float height;
};
// profオブジェクトを生成し、ポインタ作成
prof someone;
prof *someone_ptr;
someone_ptr = &someone;
std::cout << someone_ptr << "\n";
// profオブジェクトをnew演算子で生成
// personのオブジェクトに領域を割り当て、ポインタを返す。
prof *another_ptr;
another_ptr = new prof;
std::cout << another_ptr << "\n";
// 配列を割り当て
int *array_ptr;
array_ptr = new int[80];
std::cout << array_ptr << "\n";
return 0;
}
実行結果。
0012F348 00426CA0 00426EB0
ヒープ領域として、どのあたりのアドレスが確保されているのかを確認できます。
■この記事のトラックバックURL:
http://www.mapee.jp/mpe334/mt-tb.cgi/276