У меня есть следующие классы
class A{
operator<(A & object); //how do i make it so hat B < C?
};
class B: public A{
operator<(A & object);
};
class C: public A {
operator<(A & object);
};
A * ptr = new B();
A * ptr2 = new C();
if (*ptr < *ptr2) //how do I overload this?
Как я могу перегрузить < функция, чтобы он знал, что класс B меньше, чем класс C?
Как сказал Mooing Duck, когда вам нужно дианмически связать два объекта во время выполнения, вы должны использовать двойную диспетчеризацию. В этом случае мы можем сделать это просто, потому что там задействовано несколько типов.
Начните с виртуального вызова:
class B;
class C;
class A{
public:
virtual bool operator<(const A & object) const = 0; // I assume you only care about B and C
virtual bool operator<(const B & object) const = 0;
virtual bool operator<(const C & object) const = 0;
};
Затем сделайте что-то вроде этого:
class B: public A{
public:
virtual bool operator<(const A & object) const
{
// do a second bind, now that we know 'this' is type B. Negate cause we
// are switching the operands.
return !object.operator<( (const B&)*this);
}
virtual bool operator<(const B & object) const
{
//<do your logic>; // here you can assume both will be type B
}
virtual bool operator<(const C & object) const
{
return true; // B is always < than C right?
}
};
class C: public A{
public:
virtual bool operator<(const A & object) const
{
// do a second bind, now that we know 'this' is type C. Negate cause we
// are switching the operands.
return !object.operator<( (const C&)*this);
}
virtual bool operator<(const B & object) const
{
return false; // C is always > then B right?
}
virtual bool operator<(const C & object) const
{
//<do your logic>; // here you can assume both will be type C
}
};
То, что мы делаем здесь, делает динамическое связывание для каждого объекта, таким образом зная оба типа во время выполнения.
ОБНОВИТЬ:
Я немного изменил код, чтобы предотвратить бесконечную рекурсию.
Других решений пока нет …