有人可以让我摆脱痛苦吗?我试图弄清楚为什么派生 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()
(它是虚拟的,为简洁起见,这里没有显示)工作正常,但即使两个对象是. 也obj1 == obj2
总是调用.Base
operator==
Derived
我知道当我发现问题所在时我会踢自己,但如果有人能轻轻地让我失望,那将不胜感激。