C++のコンストラクタ呼び出しにハマる
ふと,
#include <iostream> using namespace std; class Sample { public: Sample() { cout<<"constructor"<<endl; } }; int main() { Sample a(); return(0); }
というプログラムを実行したときに,「constructor」と表示されなかったので,「?」と思ってしまいました.
もちろん,
int main() { Sample a; return(0); }
と変更すると,「constructor」と表示されます.この違いが分かりませんでした.
ヒントになったのは,iccではなく,g++でコンパイルしたときの,このメッセージ.
警告: the address of ‘int a()’, will always evaluate as ‘true’
確かに,
int main() { Sample a(); cout<<a<<endl; return(0); }
の実行結果は,
# g++ test.cc test.cc: In function ‘int main()’: test.cc: 警告: the address of ‘Sample a()’, will always evaluate as ‘true’ # ./a.out 1
と,確かに「1」=trueと表示されます.
要するに,クラスを陽に定義しない場合も同じでした.例えば,
int main() { int a(); cout<<a<<endl; return(0); }
とした場合も,
# g++ test.cc test.cc: In function ‘int main()’: test.cc: 警告: the address of ‘Sample a()’, will always evaluate as ‘true’ # ./a.out 1
「()」をつけると,関数宣言になるようですね.