C ++比较抽象类的后代

时间:2016-12-28 16:46:42

标签: c++ abstract-class abstract override virtual-functions

是的,我知道比较不同抽象类后代的不良基调。但我真的必须。

我有这个简单的抽象类:

class Figure {
    public:
    virtual double Square() = 0;
    virtual ~Figure() {};
}

我想要添加的内容如下:

bool operator<(const Figure& other) {};

哪个会比较它的后代 - 几何数字,即Triangle, Rectangle, Octagon - 使用它们在方法Square()中返回的区域。

这有可能吗?

1 个答案:

答案 0 :(得分:3)

根据您的评论return (*this->Square() < other->Square());,您的麻烦似乎只是基本的语法。

this是一个简单的指针。所以典型的正确语法只是this->Square()。当然因为它在一个成员函数中,所以this可以完全省略为Square()

other是一个引用,因此使用点运算符作为other.Square()

与您的最新评论可能相关的另一个有用的事情是使运营商&lt;函数const,因为它没有修改它被调用的对象。

所以生成的代码应该更像是:

bool operator<(const Figure& other) const
{
    return Square() < other.Square();
}
相关问题