[英]Passing a list in c++ as reference
我希望能夠修改列表並在main()
函數中打印它。 但我無法編譯代碼。 錯誤是當我調用myFunction()
。
另外,如何訪問函數中的列表? 在這種情況下, *it1
是否正確存儲了字符串? 或者我應該有一個像list<String *> temp
這樣的list<String *> temp
? 我希望能夠訪問列表的所有元素並將其打印出來。
int main(){
list<String> *temp = new list<String>;
myFunction(temp);//calling the function ----this is erroring
//print the elements of the list..I need not pass the pointer, since I just want to print the list? and not edit it?
printList(temp);
}
void printList(list<String> &temp){
std::list<String>::iterator it1 = temp.begin();
for (; it1 != temp.end(); ++it1)
{
printf("\n %s \n", *it1);
//is *it1 expected to print the string in this list of strings?
}
}
void myFunction(list<String> &temp){
temp.push_back("Data_1");
temp.push_back("Data_2");
}
在 C++ 中通過引用傳遞對象時,您指定對象本身,而不是指向它的指針。 在這里,您要傳遞temp
指向的列表,即*temp
。
C++ 中的函數必須在使用之前聲明。
嘗試:
void myFunction(list<String> &);
int main(){
list<String> *temp = new list<String>;
myFunction(*temp);
//print the elements of the list
}
void myFunction(list<String> &temp){
temp.push_back("Data_1");
temp.push_back("Data_2");
}
你的函數被聲明為接受一個list<String>&
引用,但你傳遞給它的是一個list<String>*
指針。 所以要么:
int main(){
list<String> temp;
myFunction(temp);
//print the elements of the list
}
int main(){
list<String> *temp = new list<String>;
myFunction(*temp);
//print the elements of the list
delete temp;
}
首先,myFunction 的聲明應該在 main 之前,因為編譯器不知道這個函數。 然后,函數參數是一個引用,但是你傳遞了一個指向它的指針,不合適。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.