【发布时间】:2013-04-01 01:41:00
【问题描述】:
我有一个程序,它将类和结构集存储在列表中。
它执行以下操作:
- 通过引用将输入(
int)、迭代器、列表和指针传递给函数check() - 迭代列表,直到找到迭代器的数据和输入之间的匹配项
- 将指针设置为迭代器的位置
- 返回真或假,取决于是否找到匹配项。
我的问题是,当我从函数检查中调用函数 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
编辑:对不起,我链接了错误的显示函数()。编辑代码更新
【问题讨论】:
-
通过引用传递到哪里?
-
bool Inspection::check(int input, T it, T2 l, P * &Ptr) 在第一个代码块中,Ptr 被推入函数的位置,然后再次退出
-
你传递给函数调用的
p是什么? -
p 是 pIT 正在迭代的类的列表
-
传递列表的整个前提和您随后仅用作局部变量的按值未初始化的迭代器需要完全重做。忘记传递列表。通过-val 传递两个迭代器(开始和结束),并可能使用
iterator_traits<It>来获取底层数据类型的属性,用作返回类型。换句话说,您正在使事情变得更加复杂。作为奖励,使用两个迭代器可以让您完全不受惩罚地交换容器。
标签: c++ list pointers return-by-reference