我正在编写一个循环列表列表的递归函数。 这是函数的标题:
void findDirToDelete(Directory*& current_dir_ptr, Directory*& dir_to_delete, int space_to_free) {
这是该问题中有趣的函数部分:
Directory* ptr = nullptr;
for (auto it : current_dir_ptr->children) {
ptr = ⁢
findDirToDelete(ptr, dir_to_delete, space_to_free);
}
此代码编译并运行。 除其他属性外,类 Directory 还包含一个
list<Directory> children
元素。
我的问题是,为什么上面的代码可以编译,但下面的代码不能编译?
for (auto it : current_dir_ptr->children) {
findDirToDelete(&it, dir_to_delete, space_to_free);
}
这是我得到的编译错误:
'void findDirToDelete(Directory *&,Directory *&,int)': cannot convert argument 1 from 'Directory *' to 'Directory *&'
我有一种感觉,这是因为该函数通过引用获取第一个元素,但我无法真正解释原因(这里有点初学者......)。
提前致谢!
你的函数的参数是一个
Directory *&
,它是一个引用。它是对指针的引用,但这是次要细节,它首先是引用。
在 C++ 中,引用不能绑定到纯右值。用不太正式、稍微不精确的术语来说,您不能将表达式作为引用参数传递。这只是 C++ 的规则之一,没有例外或解决方法。
&it
是一个产生指针的表达式。它不能绑定到引用。
ptr
是一个左值,一个命名对象。 C++ 中允许创建对命名对象的引用。