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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…