在C++中的混合对象列表中使用相同的方法

Use the same method across a list of mixed objects in C++

本文关键字:方法 对象 C++ 混合 列表      更新时间:2023-10-16

编辑:感谢您的输入 - 我意识到这比我想象的要明显得多!

假设我有许多类,所有这些类都继承自一个基类。 假设我们有ShapeCircle并且Square从中继承。Shape类有一个虚方法getArea(),然后用CircleSquare定义。

我想创建一个圆形和方形对象的列表,然后依次对列表中的每个对象调用函数getArea()

是否可以像这样将Square类和Circle类混合到单个列表对象中?如果我这样做,是否可以遍历列表中的对象,并在每个类中调用相同的命名方法?

提前非常感谢!

假设Shape是一个多态基(即它有一个或多个虚函数,派生类可以覆盖(,那么这是可能的。

例如;

  #include <vector>
  #include <memory>
   // definitions of Shape, Circle, Square, etc
  int main()
  {
      std::vector<std::unique_ptr<Shape>> shapes;
      shapes.push_back(new Circle);
      shapes.push_back(new Square);
      for (auto &s : shapes)
      {
           s->getArea();
      } 
       //   when shapes ceases to exist, so do the objects it contains
      return 0;
  }

Shape在上述内容中还必须有一个虚拟析构函数。

请注意,unique_ptr C++11 或更高版本。 您可能希望使用其他智能指针(如shared_ptr(,具体取决于您的需求。

在我发布了这个问题之后,我开始记住C++是如何工作的!我为自己写了一个示例以供将来参考 - 希望它对其他人很方便!

#include <iostream>
#include <math.h>
class Shape
{
    public:
        virtual unsigned int getArea() = 0;
};
class Circle: public Shape
{
    public:
        unsigned int getArea(){
            return M_PI * radius * radius;
        }
        int getPerimeter(){
            return 2 * M_PI * radius;
        }
    private:
        unsigned int radius = 5;
};
class Square: public Shape
{
    public:
        unsigned int getArea(){
            return side*side;
        }
    private:
        unsigned int side = 5;
};
int main(void)
{
    Circle circle1, circle2;
    Square square1, square2;
    Shape *shapes[] = {&circle1, &square1, &circle2, &square2};
    int idx;
    std::cout << "Hello!" << std::endl;
    for(idx = 0; idx < 4; idx++){
        std::cout << "Shape " << idx << " area is: "
            << shapes[idx]->getArea() << std::endl;
    }
    std::cout << "Circle1's perimeter is: "
        << circle1.getPerimeter() << std::endl;
}