【问题标题】:passing a std::ifstream to function as a pointer传递一个 std::ifstream 作为指针
【发布时间】:2013-09-21 06:23:28
【问题描述】:

对于初学者的问题,我很抱歉,但我不明白 ifstream 出了什么问题。难道不能把它发送到像指针这样的函数(见下文)吗?

这个想法是,作为一个副作用,我希望 ifstream 在函数被调用时继续前进,因此试图将其作为指针发送。

  string ID, Title, Body;

  ifstream ifs(filename);   // std::string filename

  while(ifs.good()) {
     ID = findCell(ifs)
     Title = findCell(ifs)
     Body = findCell(ifs)  
  }
}
std::string findCell(ifstream *ifs)   // changed to &
{
    char c;
    bool isPreviousQuote;
    string str;
    while(ifs.good())
    {
        ifs.read(c, 1);   // error now shows up here

        if (c == "\n") {
           break;
        }
        str.push_back(c);
    } 
    return str;
}

错误是:

invalid user-defined conversion from 'std::ifstream {aka std::basic_ifstream<char>}' 
to 'std::ifstream* {aka std::basic_ifstream<char>*}' [-fpermissive]

【问题讨论】:

  • 为了在这里解释我自己,我在这里尝试使用双引号,但没有找到当前的解决方案。
  • 我认为您真正想要的是将 std::ifstream 作为引用而不是指针传递。
  • 因为引用不是伪装的指针,而且您当地的“大师”是错误的。
  • 引用为您提供了对象实例的地址,因此您不必检查空指针。它更安全。
  • 引用更易于使用和推理。例如。您当前的代码不起作用,因为在将流传递给函数时,您没有使用运算符 &amp; 的地址。这对于参考是不必要的。此外,引用永远不能为空,因此您不太可能对它们犯错误。

标签: c++ pointers parameter-passing pass-by-reference ifstream


【解决方案1】:

你的函数需要一个指向std::ifstream对象的指针:

std::string findCell(ifstream *ifs)

指针应该使用它们将指向的内存块的地址来初始化。
在这种情况下,使用&amp; 检索到ifs 的地址:

Title = findCell(&ifs);

更好的是因为findCell函数需要ifstream的存在,所以通过引用传递更加简洁合理:

std::string findCell(std::ifstream& ifs) { ... }
...
Title = findCell(ifs);

【讨论】:

  • 或者等等,不。它向下移动到单元格内的部分。到ifs.read(c, 1) 部分。
  • 感谢您的额外解释!
  • @Dualinity 当然也可以工作(读入足够大的地址)。 IE。 jmstokers 评论。
猜你喜欢
  • 1970-01-01
  • 2012-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多