fork download
  1. #include<typeinfo>
  2. #include<iostream>
  3. using namespace std;
  4.  
  5. class Base{
  6. friend bool operator==(const Base&, const Base&);
  7. public:
  8. Base(int i) :base(i){}
  9. virtual ~Base() = default;
  10. int base;
  11. protected:
  12. virtual bool equal(const Base&) const;
  13. };
  14.  
  15. class Derived :public Base{
  16. public:
  17. Derived(int i,int j) :Base(i),derived(j){}
  18. int derived;
  19. protected:
  20. bool equal(const Base&) const;
  21. };
  22.  
  23. bool operator==(const Base &lhs, const Base &rhs)
  24. {
  25. cout << "\toperator==(base&, base&)\n";
  26. return typeid(lhs) == typeid(rhs) && lhs.equal(rhs);
  27. }
  28.  
  29. bool Derived::equal(const Base &rhs) const
  30. {
  31. cout << "\tDerived::equal(Base&)\n";
  32. auto r = dynamic_cast<const Derived&>(rhs);
  33. return derived == r.derived && (Base::equal(rhs));
  34. }
  35.  
  36. bool Base::equal(const Base &rhs) const
  37. {
  38. cout << "\tBase::equal(Base&)\n";
  39. return base == rhs.base;
  40. }
  41.  
  42. int main(){
  43. Base b1(1), b2(2);
  44. Derived d1(1, 11), d2(2, 22);
  45. if (d1 == b1)
  46. cout << "Yes";
  47. else
  48. cout << "No";
  49. cout << endl;
  50.  
  51. Derived &d3 = dynamic_cast<Derived&>(d1);
  52. cout << d3.derived;
  53. //error
  54. //Derived &d4 = dynamic_cast<Derived&>(b1);
  55. //cout << d4.derived;
  56. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
	operator==(base&, base&)
No
11