Com*_* 10 4 c++ polymorphism virtual operators equals-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 );
};
Run Code Online (Sandbox Code Playgroud)
现在当我像这样实例化和比较时......
Derived p1("Sarah", 42);
Derived p2("Sarah", 42);
bool z = ( p1 == p2 );
Run Code Online (Sandbox Code Playgroud)
... 一切都很好.这里调用了来自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;
Run Code Online (Sandbox Code Playgroud)
这里asString()
(这是虚拟的,为简洁起见,此处未显示)工作正常,但是如果两个对象都是,则obj1 == obj2
总是调用Base
operator==
偶数Derived
.
我知道当我发现什么是错的时候我会踢自己,但如果有人能让我轻轻放下,我将非常感激.