#include <iostream>
using namespace std;
class Polygon {
private:
int nrVarfuri, x[10], y[10];
public:
Polygon(){}
Polygon(const Polygon &p){}
void show()
{
cout<<"Number of tips: "<<nrVarfuri<<endl;
for(int i=1;i<=nrVarfuri;i++){
cout<<"X ["<<i<<"]="<<x[i]<<endl;
cout<<"Y ["<<i<<"]="<<y[i]<<endl;
}
};
void setValues (int nrVal, int XO[], int YO[]){
nrVarfuri = nrVal;
for(int i=1;i<=nrVal;i++){
x[i]=XO[i];
y[i]=YO[i];
}
};
};
int main ()
{
int poly,i,tips,j;
int x[tips],y[tips];
cout<<"Insert the number of polygons: "<<endl;cin>>poly;
Polygon tabPoligon[poly];
Polygon p;
for(i=0;i<poly;i++){
// cout<<"Insert the number of tips: "<<endl; cin>>tips;
cout<<"Numarul de varfuri: "<<endl; cin>>tips;
for(j=1;j<=tips;j++)
{
cout<<"X["<<j<<"]:";cin>>x[j];
cout<<"Y["<<j<<"]:";cin>>y[j];
}
p.setValues(tips,x,y);
tabPoligon[i]=p;
for(int i=0;i<poly;i++){
cout<<"\n\nThe polygon have the folowing coordinates: "<<endl;
}
tabPoligon[i].show();
}
return 0;
}
我必须插入数字的数量,从键盘插入坐标并打印它们。程序在从键盘读取坐标后显示坐标,而不是等待插入另一个多边形坐标,这是什么问题?
您的代码中有很多问题。2个专业是:
int x[tips],y[tips];
很可能初始化大小为 1 或 0 的数组,对于相同的Polygon tabPoligon[poly];
for(j=1;j<=tips;j++)
应该是for(j=0;j<tips;j++)
(在很多地方)这 2 个问题足以写到调用Undefined Behavior的数组的实际末尾。
修复此问题后,您只需关闭for(i=0...)
用于加载数据的第一个循环,然后再按照 alexeykuzmin0 在其评论中的建议打开显示循环。
对于数组,快速解决方法是像在课堂上一样使用 const 维度:int x[10], y[10]
. 对于tabPolygon
数组,您可以使用动态分配:
Polygon *tabPoligon = new Polygon[poly];
并且在返回之前不要忘记释放它 delete[] tabPoligon;
但是 C++ 的方式是在std::vector
这里使用 a 。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句