enum ShapeType
{
RECTANGLE = 1,
CIRCLE,
TRIANGLE,
MAX
};
int main()
{
int n;
std::cout << "Number of elements : ";
std::cin >> n;
std::vector <Shape *> shapes;
for(int i = 0; i < n; i++)
{
std::cout << "What shape do you want to build \n 1) Rectangle\n 2) Circle\n 3) Triangle\n" << std::endl;
int t;
// de implementat do while
std::cin >> t;
for(ShapeType i = RECTANGLE; i < MAX; i = static_cast<ShapeType>(i+1))
{
do
{
switch (t)
{
case RECTANGLE:
{
int width, height;
std::cout << "Width = "; cin >> width;
std::cout << "Height = "; cin >> height;
Shape *rect = new Rectangle(width, height);
shapes.push_back(rect);
std::cout << "Rectangle area is: " << rect->getArea() << std::endl;
std::cout << "Rectangle perimeter is: " << rect->getPerimeter() << std::endl;
rect->draw();
break;
}
case CIRCLE:
{
double radius;
std::cout << "Please give circle radius: "; std::cin >> radius;
Shape *circ = new Circle(radius);
shapes.push_back(circ);
break;
}
case TRIANGLE:
{
double l1, l2 ,l3;
std::cout << "Side 1: "; std::cin >> l1;
std::cout << "Side 2: "; std::cin >> l2;
std::cout << "Side 3: "; std::cin >> l3;
Shape *tri = new Triangle(l1, l2, l3);
shapes.push_back(tri);
break;
}
default:
break;
}
}
while(n > i);
{
break;
}
}
}
return 0;
}
我这里有一个抽象的Shape类和继承它的Rectangle,Circle和Triangle。我想介绍一下&#39; n&#39;形状的数量,并为它们做一个循环。 例如,我选择我要制作3个形状,选择它们的选项出现,选择一个形状然后再重复3次。我有这个任务,我必须使用do while。我有一些便宜的尝试,但我迷路了。有什么建议 ?
答案 0 :(得分:0)
你正在重用内循环中的索引i
,导致外循环行为不端。将其更改为另一个变量,例如j
,并更改此变量的相关用途。
答案 1 :(得分:0)
这只是一个快速解释如何做到这一点。
int n,i=0;
cout << "Enter no of elements";
cin >> n;
if( n > 0 ){
do{
int shapeType;
cout << "choose type";
cin >> shapeType;
switch(shapeType){
case RECTANGLE:
break;
case CIRCLE:
break;
...
}
++i;
}while(i<n);
}