【发布时间】: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 作为引用而不是指针传递。
-
因为引用不是伪装的指针,而且您当地的“大师”是错误的。
-
引用为您提供了对象实例的地址,因此您不必检查空指针。它更安全。
-
引用更易于使用和推理。例如。您当前的代码不起作用,因为在将流传递给函数时,您没有使用运算符
&的地址。这对于参考是不必要的。此外,引用永远不能为空,因此您不太可能对它们犯错误。
标签: c++ pointers parameter-passing pass-by-reference ifstream