我有一个程序,它在列表中存储类和结构的集合。
它执行以下操作:
- 通过引用将输入(
int
)、迭代器、列表和指针传递到函数check()
- 迭代列表,直到找到迭代器数据和输入之间的匹配
- 将指针设置为迭代器的位置
- 返回 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/