我有一个基类,我有4个派生类。当然我写了2个类,例如。 我创建了矢量并用派生类的对象填充它,然后我想要按区域函数的矢量基础排序。我想使用运算符重载。
我定义了运算符重载但不完全! 请帮我! 谢谢......
class Shape
{
public:
Shape() {}
virtual void draw() = 0;
virtual int area() = 0;
virtual void perimeter() = 0;
bool operator >(Shape * shape_one , Shape* shape_two )
{
return shape_one->area() > shape_two->area();
}
protected :
double height;
double width;
};
class Squar : public Shape
{
public:
Squar(int _width) {
width = _width;
}
void draw(){}
int area(){
return width * width;
}
void perimeter(){}
bool operator >(Squar * squar_one , Squar* squar_two )
{
return squar_one->area() > squar_two->area();
}
};
class Triangle : public Shape
{
public:
Triangle(int _width , int _height) {
width = _width;
height = _height;
}
void draw(){}
int area(){
return (width * height) / 2;
}
void perimeter(){}
bool operator >(Triangle * triangle_one , Triangle* triangle_two )
{
return triangle_one->area() > triangle_two->area();
}
};
int main()
{
Shape *rect = new Rectangular( 1 , 9);
Shape *squar = new Squar(5);
QVector <Shape *> list;
list.push_back(rect);
list.push_back(squar);
retuurn 0;
}
答案 0 :(得分:0)
我理解回答这个问题。
在基类中添加以下代码:
bool operator <( Shape *item )
{
return this->area() < item->area();
}
并在main中添加以下代码:
std ::sort(list.begin() , list.end() ,[](Shape* ptr_l , Shape* ptr_r) { return *ptr_l < ptr_r;} );
这段代码是对的! :)