运算符重载显示输出中的不规则行为

时间:2013-06-24 06:49:39

标签: c++ polymorphism virtual-functions override comparison-operators

#include <iostream>
using namespace std;
class base
{
public:
  virtual bool operator ==( const base& other ) =0;
};

class derived : public base
{
public:
  bool operator ==( const base& other ) { return false; }
  bool operator ==( const derived& other ) { return true; }
};


int main()
{
  base* a = new derived;
  base* b = a;
  std::cout << ( *a == *b ) << std::endl;
  cout<< (dynamic_cast< base*>(b) == dynamic_cast< base*>(a));

}

std::cout << ( *a == *b ) << std::endl;会调用Derived::operator==( const base& other ),但为什么cout << (dynamic_cast<base*>(b) == dynamic_cast<base*>(a));在输出中给出1?

0 个答案:

没有答案