Skip to content

Instantly share code, notes, and snippets.

@yumatsuoka
Created November 19, 2018 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yumatsuoka/827a5844d1e2bbce4266e728dfe25ab7 to your computer and use it in GitHub Desktop.
Save yumatsuoka/827a5844d1e2bbce4266e728dfe25ab7 to your computer and use it in GitHub Desktop.
2018_cpp_class_example_p124_4-5-5
#include <iostream>
using namespace std;
class samp{
int i, j;
public:
void set_ij(int a, int b){i=a; j=b;}
/* 引数1つのコンストラクタを実装して、
引数なしのコンストラクタをコメントアウトしてみる。
"no matching constructor for initialization of samp[10]"。
コンストラクタが何も定義されていない場合には、デフォルトコンストラクタが自動的に呼ばれる?
コンストラクタが1つでも定義されていた場合には、デフォルトコンストラクタは呼ばれないので、
適切なコンストラクタが無いというエラーが起きると仮定。
*/
// samp(){this->i=100; this->j=100;} // 演習2(1)で実装
// samp(int ij){this->i=ij; this->j=ij;} // 演習2(2)で実装
~samp(){cout << "デストラクタ呼び出し \n";}
int get_product(){return i*j;}
};
int main(int argc, char *argv[]){
samp *p;
int i;
p = new samp [10];
if(!p){
cout << "メモリ割り当てエラー \n";
return 1;
}
// 演習2(1)で実装
for(i=0; i<10; i++){
cout << "p[" << i << "]の初期値のi*j=" << p[i].get_product() << endl;
}
for(i=0; i<10; i++){
p[i].set_ij(i, i);
}
for(i=0; i<10; i++){
cout << "積 [" << i << "] は: ";
cout << p[i].get_product() << "\n";
}
delete [] p;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment