C ++指针,引用和函数调用

时间:2016-08-15 08:39:08

标签: c++ pointers boost reference

我是C ++的新手,我对C ++中的指针,地址和函数调用感到有点困惑。

我有以下函数调用:

config.pages= avail_pages(config.books_path, &config.books.front());

配置类有多个std::vectors<uint16_t>,例如config.books包含book id(来自books_path的文件名)。

现在我想获得第一本书的可用页面(每个页面都是一个文件)。因此,avail_pages将在books_path和第一本书中查找文件。

预订1234和第12页的有效路径如下所示:books_path / 1234/12

std::vector<uint16_t> avail_pages(std::string books_path, uint16_t* book) {

    std::vector<uint16_t> pages;

    std::string first_book;
    first_book = books_path + std::to_string(*book); //pointer or not? string concatenation?
    boost::filesystem::path p(first_book);

     for (auto i = boost::filesystem::directory_iterator(p); i != boost::filesystem::directory_iterator(); i++)
     {
             std::string s = i->path().filename().string();
             pages.push_back(std::stoi(s));
     }
  return pages;
}

问题是:如果我使用向量函数front(),它将返回对第一个元素的引用。

  1. 我是这样打电话的:&config.books.front()

  2. 如何将引用传递给函数?我是否必须使用指针,如下所示:std::vector<uint16_t> avail_pages(std::string books_path, uint16_t* book)

  3. 如何访问实际值并将其从整数转换为a 字符串?
  4. 目前我在front()函数的函数调用中遇到错误,这表明我没有理解引用/指针的事情。 提前谢谢!

1 个答案:

答案 0 :(得分:1)

如果您提供配置和书籍的定义,那就更好了。 这就是说,你需要理解的是矢量函数front()返回对向量所持有的前对象的引用,这意味着你通常会在前面调用一个类成员。 考虑一下:

class book
{
public :
std::string books_path;
uint16_t book_id;
};
std::vector <book> config;
//your declared function :
std::vector<uint16_t> avail_pages(std::string books_path, uint16_t* book);
//you'd call this as such :
avail_pages(config.front().books_path, &config.front().book_id);