誰かがこれで私を悲惨な状態から救ってくれませんか? 派生した operator== がループで呼び出されない理由を理解しようとしています。例を単純化するために、ここに私の Base クラスと Derived クラスを示します。
class Base { // ... snipped
bool operator==( const Base& other ) const { return name_ == other.name_; }
};
class Derived : public Base { // ... snipped
bool operator==( const Derived& other ) const {
return ( static_cast<const Base&>( *this ) ==
static_cast<const Base&>( other ) ? age_ == other.age_ :
false );
};
このようにインスタンス化して比較すると...
Derived p1("Sarah", 42);
Derived p2("Sarah", 42);
bool z = ( p1 == p2 );
... すべて良好。ここで Derived の operator== が呼び出されますが、リストをループすると、ポインタのリスト内の項目が Base オブジェクトに比較されます ...
list<Base*> coll;
coll.push_back( new Base("fred") );
coll.push_back( new Derived("sarah", 42) );
// ... snipped
// Get two items from the list.
Base& obj1 = **itr;
Base& obj2 = **itr2;
cout << obj1.asString() << " " << ( ( obj1 == obj2 ) ? "==" : "!=" ) << " "
<< obj2.asString() << endl;
ここasString()
(これは仮想であり、簡潔にするためにここには示していません) は正常に動作しますが、2 つのオブジェクトが であってもobj1 == obj2
常に を呼び出します。Base
operator==
Derived
何が悪いのか分かったら自分を蹴ってしまうことはわかっていますが、誰かが私を優しく失望させてくれるなら、それは大歓迎です.