指针和类有问题。两个相同的类,其中一个有效,一个有效

时间:2016-02-07 16:42:56

标签: c++

好的,所以我在处理一个项目时遇到了一些麻烦。我需要两个类来形成多变量类(或结构)的链表。第一个称为gps的工作正常。它应该将x和y坐标读入一个位置,然后将其添加到链接列表中。这完全没问题,如下所示:

ifstream in;
location *tail = NULL;
location *head = NULL;

gps::gps()
{
    tail = NULL;

    in.open("coordinates.txt");
    if(in.fail())
    {
        std::cout << "Unopen to open coordinates.txt" << std::endl;
    }
    while (!in.eof())
    {
        getLocation();
    }
    in.close();
}

void gps::getLocation()
{
    location o;
    in >> o.xcoordinate;
    in >> o.ycoordinate;
    addToTail(o);
}

void gps::addToTail(location a)
{
    location *newlocation = new location();
    newlocation->xcoordinate = a.xcoordinate;
    newlocation->ycoordinate = a.ycoordinate;
    newlocation->next = NULL;

    if (tail == NULL)
    {
        head = tail = newlocation;
    }
    else
    {
        tail->next = newlocation; // now the next of old tail is the new location
        tail = newlocation;       // the new location should become the new tail
    }
}

所以这一切都运行正常,但现在我需要一个相同的一个来做同样的事情,但它必须创建一个加速度(x,y和z)的链表,从文件中读取的值。但是,它会在崩溃之前返回第一组坐标。查看这两个类,它们看起来与用于存储数据的位置和加速类相同。为什么第一个工作,而第二个不工作?我觉得错误来自我的指针系统,但我无法弄清楚它有什么问题。 这是传感器类,问题来自:

ifstream in_2;

sensor::sensor()
{
    acceleration *head = NULL;
    acceleration *tail = NULL;



    in_2.open("acceleration.txt");
    if(in_2.fail())
    {
        cout << "Unopen to open acceleration.txt" << std::endl;
    }
    while (!in_2.eof())
    {
        getAcceleration();
    int f;
    cin >> f;
    }
    in_2.close();
}

void sensor::getAcceleration()
{
    acceleration o;
    in_2 >> o.x;
    in_2>> o.y;
    in_2>>o.z;
    addToTail(o);
}

void sensor::addToTail(acceleration a)
{
    acceleration *newacceleration = new acceleration();
    newacceleration->x = a.x;
    newacceleration->y = a.y;
    newacceleration->z = a.z;
    newacceleration->next = NULL;
    cout << a.x <<a.y<<a.z;
    if (tail == NULL)
    {
         head = tail = newacceleration;
    }
    else
    {
        tail->next = newacceleration; // now the next of old tail is the new location
        tail = newacceleration;       // the new location should become the new tail
    }

}

我觉得错误就在“cout&lt;&lt; a.x&lt;&lt; a.y&lt;&lt; a.z;”这一行的某处。因为这一行确实打印了正确的值。希望有人能帮助告诉我这里发生了什么!被困了很长时间。

编辑:

accelaration.txt:

1 1 1
0 7 11
1 7 10
2 6 40
1 7 -33
0 7 12

coordinates.txt:

    53.344384 -6.261056
    53.344424 -6.260818
    53.344450 -6.260614
    53.344476 -6.260324
    53.344501 -6.260088
    53.344537 -6.259906

1 个答案:

答案 0 :(得分:2)

你有

newacceleration->y = a.y;

两次。第二个需要是:

newacceleration->z = a.z;

更新:传感器()中的这两行是什么?

int f;
cin >> f;