2012-06-03 39 views
0

我正在制作一个函数,用于引用文件系统上的路径并递归地将文件名添加到矢量。但首先,我必须能够向矢量添加路径。C++将解除引用的对象推向向量

这种方法有什么问题?

namespace filesys = boost::filesystem; 

方法:

void recursive_file_list(filesys::path & root_path, vector<filesys::path> & paths) { 
    paths->push_back(*root_path); // line 14 

    // TODO: add more logic to actually recurse through file system 
    // for now just add root_path (even though root_path is path of directory, not file) 
} 

我叫它像这样:

int main(int argc, char* argv[]) { 

     // Use the command line arguments 
     filesys::path abs_path; // line 23 
     if (argc > 1) 
      // Make the system complete this path to absolute path 
      abs_path = filesys::system_complete(filesys::path(argv[1])); 
     else { 
      // If no arguments given 
      cout << "usage: list_files [path]" << endl; 
      exit(1); 
     } 

     // Is this a valid path? 
     if (!filesys::exists(abs_path)) { 
      cout << "The path you have specified does not exist." << endl; 
      exit(2); 
     } 

     // If this is a directory 
     vector<filesys::path> filepaths(); 
     if (filesys::is_directory(abs_path)) { 
      cout << "You have specified a directory." << endl; 
      recursive_file_list(&abs_path, &filepaths); 
     } 

     else { 
      cout << "You have specified a file." << endl; 
     } 
    } 

错误:

list_files.cpp: In function 'void recursive_file_list(boost::filesystem3::path&, std::vector<boost::filesystem3::path, std::allocator<boost::filesystem3::path> >&)': 
list_files.cpp:14: error: base operand of '->' has non-pointer type 'std::vector<boost::filesystem3::path, std::allocator<boost::filesystem3::path> >' 
list_files.cpp:14: error: no match for 'operator*' in '*root_path' 
list_files.cpp: In function 'int main(int, char**)': 
list_files.cpp:43: error: invalid initialization of non-const reference of type 'boost::filesystem3::path&' from a temporary of type 'boost::filesystem3::path*' 
list_files.cpp:13: error: in passing argument 1 of 'void recursive_file_list(boost::filesystem3::path&, std::vector<boost::filesystem3::path, std::allocator<boost::filesystem3::path> >&)' 

我不明白 - 我传递通过引用,然后解引用它来添加它......不确定wh在我做错了。

+3

为什么-1?我用C++并不是很好,但我不认为这意味着我不应该问这个问题。 – lollercoaster

回答

4

您无法取消引用! *->运营商不适用于引用;你将自己推pathvector本身:

paths.push_back(root_path); // line 14 

,此外,你不通过地址引用参数,只是参数本身,所以你会这样调用该函数:

recursive_file_list(abs_path, filepaths); 

引用本身都有类似指针的非复制语义;你不需要通过接收地址或尝试解除引用来帮助他们。

+0

但是我想将'path'的值添加到矢量中.. – lollercoaster

+1

事实上,这就是会发生的事情。因为'recursive_file_list()'的参数是引用参数,'recursive_file_list()'中的'push_back'影响'main()'中声明的'vector'。这就是参考参数的全部要点! –

+0

我的想法是,因为我传入的'path'是一个引用,那么向该变量添加该向量就会添加一个引用。 C++在添加之前是否自动解引用它? – lollercoaster