派生类中的运算符==永远不会被调用

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.

我知道当我发现什么是错的时候我会踢自己,但如果有人能让我轻轻放下,我将非常感激.

R S*_*hko 9

那是因为您没有使您的运算符==虚拟,因此在运行时不考虑实际类型.

不幸的是,只是让运营商==虚拟无法解决您的问题.原因是当您通过将参数的类型从base更改为derived来更改函数签名时,实际上是在创建一个新函数.听起来你想要调查双重调度来解决你的问题.

  • @McWafflesitx - 你的信念不正确. (4认同)