所以我得到了这个例子:
class figures
{};
class square:public figures
{};
class circle : public figures
{};
.....
int main()
{
geometric figures* *p;
p[0]=new Circle;
p[1]=new Square;
return 0;
};
等等。我的问题是,如果所有指针都是几何图形类型,我怎么能在后面找到我的几何图形数组中有多少个圆或正方形呢?
答案 0 :(得分:1)
您可以使用dynamic_cast
:
std::vector<geometric_figures *> shapes;
int num_circles = 0;
int num_squares = 0;
for (geometric_figures * shape : shapes)
{
if(dynamic_cast<circle*>(shape))
num_circles++;
if(dynamic_cast<square*>)(shape))
num_squares++;
}
您还可以添加enum
以对应形状类型,并添加返回GetType()
的{{1}}方法。
答案 1 :(得分:1)
你班上可以有enum
class geometric_figures
{
public:
enum shape {eSquare, eCircle};
virtual shape GetShapeType() const = 0;
};
class square : public geometric_figures
{
public:
shape GetShapeType() const override { return eSquare; }
};
class circle : public geometric_figures
{
public:
shape GetShapeType() const override { return eCircle; }
};
然后您可以使用std::count_if
#include <algorithm>
#include <vector>
int main()
{
using GF = geometric_figures;
std::vector<GF*> p;
p.push_back(new circle);
p.push_back(new square);
int num_circles = std::count_if(p.begin(), p.end(), [](GF const* fig){ return fig->GetShapeType() == GF::eCircle; });
}
答案 2 :(得分:0)
您可以使用动态强制转换。例如:
// Returns true if 'a' is of type 'square'
bool isSquare(Figure* a)
{
return dynamic_cast<Square*>(a) != nullptr;
}
// Returns true if 'a' is of type 'circle'
bool isCircle(Figure* a)
{
return dynamic_cast<Circle*>(a) != nullptr;
}
int main()
{
Figure *p = new Figure[5];
p[0] = new Circle;
p[1] = new Circle;
p[2] = new Square;
p[3] = new Square;
p[4] = new Square;
int circleCnt = 0;
int squareCnt = 0;
for(int i = 0; i < 5; i++)
{
if(isCircle(p[i]))
{
circleCnt++;
}
if(isSquare(p[i]))
{
squareCnt++;
}
}
cout << "Number of circles: " << circleCnt << endl;
cout << "Number of squares: " << squareCnt << endl;
}
该程序的输出为:
圆圈数:2
平方数:3
请注意这是非常低效的与保持圆圈和方块的数量在某处保持最新状态相比。