C++ 指针引用、类和指针列表、奇怪的返回

标签 c++ list pointers return-by-reference

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

它执行以下操作:

  1. 通过引用将输入(int)、迭代器、列表和指针传递到函数 check()
  2. 迭代列表,直到找到迭代器数据和输入之间的匹配
  3. 将指针设置为迭代器的位置
  4. 返回 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 是一个函数,它与正在迭代的类中的私有(private)数据进行比较,例如

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

显示也很简单

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)     

关于C++ 指针引用、类和指针列表、奇怪的返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15736553/

相关文章:

c++ - 用不同的值初始化 vector

c++ - 静态常数整数数组

c# - 在 'foreach' 循环中使用 LINQ 仅运行一次

c# - 如何使用字符串列表作为列表框的数据源

c++ - 结构可以具有类型 `Card*` 吗? (书中的例子)

c - 使用指针返回修剪后的字符串

delphi - 如果 "dangling pointers"检测不到,如何检测 "Assigned()"?

c++ - Armadillo :从稀疏矩阵中获取稀疏行 vector 的非零位置

c++ - 运行时检查失败 #2 - 变量 'arr' 周围的堆栈已损坏。我试图找到它,但仍然找不到我出界数组的位置

java - 如何在java中从外部更改/更新方法?