C++ 2d动态对象数组

c++ 2d dynamic array of objects

此代码从文件中读取数据,我想将其保存到 class 图形类型的二维动态对象数组中 当我尝试检查对象数组 g 的内容时,它是空的...请帮助我将数据保存到数组中。

class graph
{
public:
    int index;
    int c;
    int p1;
    int p2;
    int s1;
    int s2;
    int t1;
    int t2;
    int weight;
    bool ready;
    graph(int index,int c, int p1, int p2, int s1, int s2,int t1, int t2, int weight,int ready)
    {
        index = index;
        c = c;
        p1 = p1;
        p2 = p2;
        s1 = s1;
        s2 = s2;
        t1 = t1;
        t2 = t2;
        weight = weight;
        ready = ready;
    }

};

这是主要代码

int main(){     char argc[20];  int m,index,c,p1,p2,s1,s2,t1,t2,weight,ready;   //graph temp(0,0,0,0,0,0,0,0,0,0);  fstream f;

    cout << "Input file name: "; cin >> argc;       f.open(argc, ios::in);  f >> m;

    graph **g=new graph*[m];        int i = 1;  while (!f.eof())    {

        f >> index >> c >> p1 >> p2 >> s1 >> s2 >> t1 >> t2 >> weight >> ready;         g[i] = new graph(index, c, p1, p2, s1, s2, t1, t2, weight, ready);
            cout<< g[i]->index; 
            i = i + 1;

            } return 0; }

你的对象初始化问题,简化:

class graph
{
   public:
      int index;
      graph(int index)
      {
         index = index;
      }
};

在上面的简化案例中,行

         index = index;

没有做任何有用的事情。这是自我分配。 LHS 上的 index 不是成员变量。这是论点。成员变量仍未初始化

您可以使用:

      graph(int index)
      {
         this->index = index;
      }

更好的是,我建议使用:

      graph(int index) : index(index) {}

对所有成员变量进行更改。