次のコードは無限ループに入ります。
#include <string>
#include <iostream>
using namespace std;
class A{
public:
A(){
cout << "Normal constructor" << endl;
}
A(const A& moo){
cout << "It's a constructor!" << endl;
operator=(moo);
}
void operator=(const A& moo){
cout << "Calling A::Operator=" << endl;
}
};
class B : public A{
public:
B(){}
B(const A& thea){
cout << "Gotshere" << endl;
operator=(thea);
}
};
int main(){
B b;
b = A();
}
無限ループの出力は、「通常のコンストラクター」と「Gotshere」の間を循環します。クラスに anをmain
割り当てるときに、存在しないを呼び出そうとする関数から推測しているので、代わりに再度呼び出します。A
B
B::operator=
B(const A&)
私が得られないのは、なぜA()
呼び出されるのかです。誰か知っていますか?EDITはこれを明確にする必要があり、無限ループで繰り返しA()
呼び出されます。
もちろん、修正は置くことB::operator=(const A&)
ですが、なぜそれをしているのか知りたいです。
さらに、 class の演算子を追加しましたB
:
void B::operator=(const A&) { cout << "That should fix things. A::Operator=" << endl; }
そして、問題は修正されましたが、修正すると、「B::operator=」の代わりに出力がB b; b = B()
得られます。Calling A::operator=
何故ですか?