c++指针引用,类和指针的列表,奇怪的返回

C++ Pointer by Reference, lists of classes and Pointers, wierd return

本文关键字:指针 列表 返回 引用 c++      更新时间:2023-10-16

我有一个程序,它在列表中存储类和结构的集合。

执行以下操作:

  1. 通过引用传递一个输入(一个int)、一个迭代器、一个列表和一个指针到函数check()
  2. 迭代列表,直到找到迭代器的数据与输入
  3. 之间的匹配。
  4. 将指针设置为迭代器的位置
  5. 返回true或false,取决于是否找到匹配项。

我的问题是,当我从函数检查内调用函数display()时,无论是来自it->display()还是Ptr->display(),它都能正常工作。但是当它通过引用传递回来时,我试着显示它。它打印垃圾。

//it is the iterator, l is the list, Ptr is the passed pointer
template<class T, class T2, class P>
bool Inspection::check(int input, T it, T2 l, P * &Ptr)
{
    for(it = l.begin(); it != l.end(); ++it){   //Iterates through list using iterator
        if (it->checkExists(input)){        //if input == iterator class's data
            Ptr = &*it;
            //Display data - ERROR CHECKING//
            it->display();          
            Ptr->display();
            return true;
        }
    }
    return false;
}

checkExists是一个函数,它与正在迭代的类中的私有数据进行比较,例如

bool Property::checkExists(int input)
{
    if (input == ID)
        return true;
    return false;
}

display也很直接

void Property::display()
{
    //Prints out property info
    cout << ID << ";" << address << ";" << landTypes[type] << ";" << price << endl;
}

标准调用是(p是我之前在程序中调用的Property类的列表)

int input;
Property * temp; //Pointer to a class temp
list<Property>::iterator pIT;
cin >> input;

while(!check(input, pIT, p, temp)){
    ...
}
    temp->display();

典型的输出是(前两个是函数内部的调用,第三个是函数外部的temp->display();调用。

1001;5/10 Northfields Ave, North Wollongong, NSW 2500;Townhouse;280000
1001;5/10 Northfields Ave, North Wollongong, NSW 2500;Townhouse;280000
13;�������314���@�ve, North Wollongong, NSW 2500;Townhouse;280000
编辑:对不起,我链接了错误的显示函数()。编辑代码更新

不考虑WhozCraig指出的设计问题,您提供的代码中打印垃圾的问题如下:

 template<class T, class T2, class P>
 bool Inspection::check(int input, T it, T2 l, P * &Ptr)
                                         ^^^^

您通过值而不是通过引用传递l,因此您将返回一个指向临时变量的指针,当您在方法外部解引用它时,该变量将不存在。如果你修改代码如下,它应该开始工作,为这个特定的问题,尽管它确实需要重新设计:

template<class T, class T2, class P>
bool Inspection::check(int input, T it, T2 &l, P * &Ptr)