在C++中的混合对象列表中使用相同的方法
Use the same method across a list of mixed objects in C++
编辑:感谢您的输入 - 我意识到这比我想象的要明显得多!
假设我有许多类,所有这些类都继承自一个基类。 假设我们有Shape
,Circle
并且Square
从中继承。Shape
类有一个虚方法getArea()
,然后用Circle
和Square
定义。
我想创建一个圆形和方形对象的列表,然后依次对列表中的每个对象调用函数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;
}
相关文章:
- 使用std::函数映射对象方法
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 按对象的特定方法按升序排列的C++优先级队列
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 从父类方法返回子类对象
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 为什么此派生对象无法访问基类的后递减方法?
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 正在调用shared_ptr对象方法
- 将方法转换为调用该方法的成员函子对象会导致崩溃
- 检查哪个对象调用了另一个对象的对象方法
- CPU 瓶颈;处理具有许多非静态对象的 3D 场景渲染的简单方法
- 直接在 unordered_map 的方法中使用哈希,而不是生成哈希的用户定义对象
- 没有取消引用/解包对象的标准方法?
- 使用 gmock c++ 在真实对象上调用方法
- 当我调用对象的方法时,对象的成员会发生变化
- 根据对象类调用不同的方法
- 如何在C++中循环访问未知对象方法?
- 使用动态实例化的对象填充矢量的快速方法
- 对类中的对象使用方法