c++ - 如何对抽象类对象进行排序

标签 c++ sorting inheritance polymorphism

我有一个基本抽象类 Shapes,以及 3 个派生类 Circle Square 和 Rectangle。在计算出所有形状的面积后,我需要对它们进行排序。我在库中使用 std::sort 进行排序时遇到困难,因为我的 Shapes 是一个抽象类。 希望有人能指出我做错事的正确方向。

我尝试过运算符重载,声明我自己的比较器函数。

#define MAX 100
class ShapeTwoD
{
protected: 
    string name;
    double area;

public:
    ShapeTwoD() {}
    ShapeTwoD(string name, double area);
    virtual ~ShapeTwoD() {}

    string getName();

    virtual string toString();

    virtual double getArea() = 0;
    virtual void setArea(double area) = 0;
    virtual double computeArea() = 0;
};
bool sortAsc(ShapeTwoD *s1, ShapeTwoD *s2)
{
    return s1->getArea() < s2->getArea();
}



class Square: public ShapeTwoD
{
public:
    Square() {}
    Square(string name, double area);
    ~Square() {}

    virtual double getArea();
    virtual void setArea(double area);

    virtual string toString();

    virtual double computeArea();
};

int main()
{
   ShapeTwoD * ShapeArray[MAX];
   string name;
   double area;
   int Shapeindex;
   for( int i = 0; i < 10; i++)
   {
        cin << name;
        cin << area;
        if (name == "Square" || name == "square")
        {
            ShapeArray[Shapeindex] = new Square(name, area);
        }
    Shapeindex++;
    }
    sort(ShapeArray, ShapeArray + MAX, sortAsc);
}

以上代码的实际结果:读取访问冲突错误,我假设它是因为我试图从我的抽象类而不是我的派生类中读取该区域。

最佳答案

(最新更新后):您正在创建 10 个 ShapeTwoD 对象,但对 100 (MAX) 个指针进行排序。

关于c++ - 如何对抽象类对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54594271/

相关文章:

delphi - 如何在派生类型中使用泛型方法

c++ - 从特定代码部分跳转到函数开始

python - Torch.sort 和 argsort 在相同元素的情况下随机排序

java - 我的 java 数组代码表现得很有趣

c++ - 向下转换指向成员函数的指针。这是合法的用法吗?

C++/Java 继承 vs. 委托(delegate) vs. 等等

c++ - 对类方法的 undefined reference

c++ - 在C++中为类分配内存

c++ - CFLocaleCopy当前陈旧值

c - 给定一个由偶数和奇数组成的数组。先对数组进行排序,然后是赔率。数字的顺序不能改变