【问题标题】:How to filter inherited objects?如何过滤继承的对象?
【发布时间】:2022-01-21 12:15:11
【问题描述】:

我有 Set 类,它由动态分配的 IShape 组成,其中 IShape 由 Square、Rectangle 等继承,我需要创建过滤函数来创建仅特定类型的新集(例如 Squares)。基本上是通过现有的集合并只选择以某种方式定义的形状(通过参数?)并创建该形状的新集合。这怎么可能?

【问题讨论】:

标签: c++ inheritance polymorphism multiple-inheritance


【解决方案1】:

为避免使用dynamic_cast,让您的IShape 类声明一个名为(比如)GetTypeOfShape 的纯虚函数。然后在每个派生类中覆盖它以返回每个代表的形状类型(例如enum)。然后你可以在你的过滤器函数中测试它并进行相应的操作。

示例代码:

#include <iostream>

class IShape
{
public:
    enum class TypeOfShape { Square, Rectangle /* ... */ };
    
public:
    virtual TypeOfShape GetTypeOfShape () = 0;
};

class Square : public IShape
{
public:
    TypeOfShape GetTypeOfShape () override { return TypeOfShape::Square; } 
};

class Rectangle : public IShape
{
public:
    TypeOfShape GetTypeOfShape () override { return TypeOfShape::Rectangle; } 
};

// ...

int main ()
{
    Square s;
    Rectangle r;
    
    std::cout << "Type of s is: " << (int) s.GetTypeOfShape () << "\n";
    std::cout << "Type of r is: " << (int) r.GetTypeOfShape () << "\n";
}

输出:

s的类型是:0
r 的类型是:1

Live demo

【讨论】:

  • 如何将枚举参数传递给函数(int 除外)?
  • 例如void foo (IShape::TypeOfShape t) { ... }。类枚举适用于街区中的酷孩子,因为它们不会污染全局命名空间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
  • 2012-01-05
  • 2011-10-08
相关资源
最近更新 更多