-1

可能重复:
C++ 如何对数组变量进行排序

我接到了家长班的电话

Shape

形状得到了 2 个孩子的电话

Square and Rectangle

Shape类有一个变量调用区,它是int类型

所以我像这样创建了一些正方形,矩形的对象

int main()
{
    Shape *shaped[100];

    //then i did some adding of object..
    int areaValue;
    areaValue=1;

    shaped[0] = new Rectangle();
    shaped[0]->setArea(areaValue);

    areaValue=7;
    shaped[1] = new Square();
    shaped[1]->setArea(areaValue);

    areaValue=5;
    shaped[2] = new Square();
    shaped[2]->setArea(areaValue);

    shapeCounter = 3;


     sort(shaped, shaped + 3, sort_by_area());


    for (int i=0;i<shapeCounter;i++)
    {
        cout << shaped[i].getArea() << endl;
    }

}

然后在例如 Square.cpp

我做了这个

struct sort_by_area
{
    static bool operator()(Shape* x, Shape* y)
    {
        return x->getArea() < y->getArea();
    }
};

上面的代码有效。并且可以按区域排序,但我的问题是,如果我不使用 struct 我仍然可以排序,因为如果我不使用 struct,它会说 sort_by_area 没有在范围内声明。

我必须真的使用 struct 以便我的 main.cpp 可以访问位于子类 .cpp 的排序代码

谢谢

4

1 回答 1

5

这完美地工作:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

class Shape{

private:
    int x;
public:
    void setArea(int x){
        this->x =  x;
    }
    int getArea(){
        return this->x;
    }
};

class Rectangle: public Shape{
public:
};

class Square: public Shape{
public:
};

bool sort_by_area (Shape* x,Shape* y) { return (x->getArea() < y->getArea()); }
int main()
{
    Shape *shaped[100];

    //then i did some adding of object..
    int areaValue,shapeCounter = 0;
    areaValue=1;

    shaped[0] = new Rectangle();
    shaped[0]->setArea(areaValue);

    areaValue=7;
    shaped[1] = new Square();
    shaped[1]->setArea(areaValue);

    areaValue=5;
    shaped[2] = new Square();
    shaped[2]->setArea(areaValue);

    shapeCounter = 3;


    sort(shaped, shaped + 3, sort_by_area);


    for (int i=0;i<shapeCounter;i++)
    {
        cout << shaped[i]->getArea() << endl;
    }
    return 0;
}
于 2012-11-04T07:37:13.707 回答