私はコンストラクタと代入演算子の使い方を理解しようとしています。私はこのプログラムでこれを試しています。なぜオーバーロードされた代入演算子を呼び出すときにコピーコンストラクタが呼び出されますか?
#include <iostream>
using namespace std;
class myclass {
int x;
public:
myclass (int p) {
cout << "calling constructor" << endl;
x = p;
}
myclass() {
cout << "calling constructor with no arguments" << endl;
x = 0;
}
myclass (myclass &t) {
cout << "calling copy constructor" << endl;
x = t.x;
}
myclass operator=(myclass &t) {
cout << "calling assignment operator" << endl;
x = t.x;
return *this;
}
void show() {
cout << "val = " << x << endl;
}
};
int main() {
myclass a1;
a1.show();
myclass a2 = a1;
a2.show();
myclass a3(a2);
a3.show();
myclass a4(200);
a2 = a4;
a2.show();
return 0;
}
出力:
calling constructor with no arguments // call 1
val = 0
calling copy constructor // call 2
val = 0
calling copy constructor // call 3
val = 0
calling constructor // call 4
calling assignment operator // call 5
calling copy constructor // call 6 i am not able to understand this print line
val = 200
コール1、MyClassのA1から行われます。
コール2は、myclass a2 = a1から実行されます。
コール3は、myclass a3(a2)から実行されます。
コール4は、myclass a4(200)から実行されます。
コール5は、a2 = a4から行われます。
しかし、私は、コール6は、それは命令から呼び出されたどこから来ている取得することはできませんよ。
a2 = a4;
しかし、それはどのようにコンストラクタをコピーするコールを与えるのだろうか?
ヘルプ/ポインタは大きな助けになるでしょう。私はcからcppに潜入していますので、私に同行してください。
あなたは= 'だけでなく'オーバーロードしています。それはそこから来ている。 –
はい、printステートメント "呼び出し代入演算子"が起きています。これは呼び出し5です。しかし、なぜ6を呼び出しますか?どこから呼び出されたのでしょうか? –
コピー代入演算子は参照を返す必要があります。 –