コピーコンストラクタ
当たり前といえば当たり前なんだけど確認。
#include <iostream> using namespace std; struct A { double x; A () : x(0.0) {} A (A &a) { cout << "copy constructor of A" << endl; x = a.x; } A &operator= (double xx) { cout << "operator= of A" << endl; x = xx; } }; struct B { A a; }; int main () { B b; cout << "b.a = 2;" << endl; b.a = 2; cout << "B bb = b;" << endl; B bb = b; return 0; }
実行。vimから直接。
:!g++ % :!./a.out b.a = 2; operator= of A B bb = b; copy constructor of A
つまり、デフォルトのコピーコンストラクタはメンバ変数のコピーコンストラクタを呼ぶ。
operator=()は別に必要なかったけど、なんとなく試してみた。