0

我有以下课程

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 类?

4

1 回答 1

0

正如 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
    }
};

我们在这里为每个对象做一个动态绑定,因此在运行时知道这两种类型。

更新:我稍微更改了代码以防止无限递归。

于 2012-11-20T01:13:56.917 回答