是的,我知道比较抽象类的不同后代是不好的语气。但我真的必须这样做。
我有这个简单的抽象类:
class Figure {
public:
virtual double Square() = 0;
virtual ~Figure() {};
}
我想添加的是这样的:
bool operator<(const Figure& other) {};
它将比较其后代 - 几何图形,即 Triangle、Rectangle、Octagon
- 使用方法 Square()
中返回的面积。
这有可能吗?
来自您的评论 return (*this->Square() < other->Square());
您的问题似乎只是基本语法。
this
是一个简单的指针。所以典型的正确语法就是 this->Square()
.当然,因为它在成员函数中,所以 this
可以完全省略,就像 Square()
.
other
是一个引用,因此使用点运算符作为 other.Square()
另一个可能与您的最新评论相关的有用的事情是使 operator< 函数 const
因为它没有修改被调用的对象。
所以生成的代码应该更像:
bool operator<(const Figure& other) const
{
return Square() < other.Square();
}