#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;
}我必须插入数字的数目,从键盘插入坐标并打印出来。程序是在从键盘上读取坐标后显示的,而不是等待插入另一个多边形坐标,有什么问题吗?
发布于 2017-07-06 10:41:28
您的代码中有许多问题。这两个专业是:
int x[tips],y[tips];很可能初始化大小为1或0的数组,与Polygon tabPoligon[poly];相同for(j=1;j<=tips;j++)应该是for(j=0;j<tips;j++) (在许多地方)这两个问题足以编写调用未定义行为的数组的实际结束。
修复后,您只需关闭用于加载数据的第一个for(i=0...)循环,然后按照alexeykuzmin0在其注释中的建议打开显示数据。
对于数组,一个快速的修复方法是使用const维度,就像您在类中所做的:int x[10], y[10]。对于tabPolygon数组,可以使用动态分配:
Polygon *tabPoligon = new Polygon[poly]; 在返回delete[] tabPoligon;之前不要忘记释放它
但是C++的方法是在这里使用一个std::vector。
https://stackoverflow.com/questions/44946051
复制相似问题