是的,我知道比较抽象类的不同后代是不好的。但是我真的必须这么做。
我有这个简单的抽象类:
class Figure {
public:
virtual double Square() = 0;
virtual ~Figure() {};
}
我要添加的内容是这样的:
bool operator<(const Figure& other) {};
它将比较其后代-几何图形-即Triangle, Rectangle, Octagon
使用method中返回的面积Square()
。
有可能吗?
从您的评论来看,您return (*this->Square() < other->Square());
的麻烦似乎只是基本语法。
this
是一个简单的指针。因此,典型的正确语法是just this->Square()
。当然,由于它位于成员函数内部,this
因此可以完全删除,就像just一样Square()
。
other
是参考,因此将点运算符用作 other.Square()
另一个可能与您的最新注释相关的有用的事情是使operator <函数const
生效,因为它没有修改被调用的对象。
因此,生成的代码应类似于:
bool operator<(const Figure& other) const
{
return Square() < other.Square();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句