Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

c++ - implementing operator== when using inheritance

I have a base class which implements the == operator. I want to write another class, inheriting the base class, and which should reimplement the == operator.

Here is some sample code :

#include <iostream>
#include <string>

class Person
{
public:
  Person(std::string Name) { m_Name = Name; };

  bool operator==(const Person& rPerson)
  {
    return m_Name == rPerson.m_Name;
  }

private:
  std::string m_Name;
};

class Employee : public Person
{
public:
  Employee(std::string Name, int Id) : Person(Name) { m_Id = Id; };

  bool operator==(const Employee& rEmployee)
  {

    return (Person::operator==(rEmployee)) && (m_Id == rEmployee.m_Id);
  }

private:
  int m_Id;
};

void main()
{
  Employee* pEmployee1 = new Employee("Foo" , 1);
  Employee* pEmployee2 = new Employee("Foo" , 2);

  if (*pEmployee1 == *pEmployee2)
  {
    std::cout << "same employee
";
  }
  else
  {
    std::cout << "different employee
";
  }

  Person* pPerson1 = pEmployee1;
  Person* pPerson2 = pEmployee2;

  if (*pPerson1 == *pPerson2)
  {
    std::cout << "same person
";
  }
  else
  {
    std::cout << "different person
";
  }
}

This sample code give the following result :

different employee
same person

Where I would like, even when handling Person* pointers, to make sure they are different.

How am I supposed to solve this problem ?

Thanks !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want to do is essentiall "virtualize" the comparison operator.

Since operators cannot be virtual (operators can be virtual), you will need to delegate it to something else. Here's one possible solution.

class Person
{
   public:
      /* ... */
      bool operator==(const Person& rhs)
      {
         return m_Name == rPerson.m_Name && this->doCompare(rhs);
      }
   private:
      virtual bool doCompare() = 0;
   };
}
class Employee : public Person
{
   /* ... */
   private:
      virtual bool doCompare(const Person& rhs)
      {
         bool bRetval = false;
         const Employee* pRHSEmployee = dynamic_cast<const Employee*>(&rhs);
         if (pEmployee)
         {
            bRetval = m_Id == pRHSEmployee->m_Id
         }
         return bRetval;
      }
};

The question didn't make clear whether Person needs to be a concrete class. If so, you can make it not pure-virtual, and implement it to return true.

This also uses RTTI, which you may or may not be happy with.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...