如何重载运算符<面向对象的层次结构?

时间:2012-11-20 00:25:20

标签: c++ object polymorphism overloading oop

我有以下课程

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?

如何重载&lt;函数,以便它知道B类小于C类?

1 个答案:

答案 0 :(得分: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
    }
};

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

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

相关问题