在C++中将ifstream传递给函数

3

我正在为一个基因测序项目构建16个不同的后缀树。它们是在主函数中这样构建的:

int main()
{  
  ifstream fp;  
  fp.open("filepath", ifstream::in);  
  Tree I(fp);  
  fp.close();

我尝试使用以下代码在我的构造函数中使用它们:

Tree::Tree(ifstream &fp)   
{  
  string current = "";  
  char* line;  
  fp.getLine(line, 100); //ignore first line  
  for(int i=0; i<100; i++)     
    {  
      char temp = (char)fp.get();  
      if(temp=='\n')i--;  
      else current+=temp;  
    }  
  insert(current);  
  while(fp.good())  
    {  
      current = current.substr(1,99);  
      char temp = (char)fp.get();  
      if(temp=='\n')temp=(char)fp.get();  
      if(temp==EOF) break;  
      current+=temp;  
      insert(current);  
    }  
}  

当我尝试编译时,每次使用fp时都会出现以下错误:
suffix.cpp: 在构造函数Tree::Tree(std::ifstream&)中:
suffix.cpp:12: 错误:无效使用未定义类型的struct std::basic_ifstream<char, std::char_traits<char> >
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd:89: 错误:声明了struct std::basic_ifstream<char, std::char_traits<char> >
suffix.cpp:15: 错误:无效使用未定义类型的struct std::basic_ifstream<char, std::char_traits<char> >
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/iosfwd:89: 错误:声明了struct std::basic_ifstream<char, std::char_traits<char> >
2个回答

7
你是否已经包含了fstream头文件?

+1. std::basic_ifstream<iosfwd> 中被前向声明,但在代码所在的源文件中实际上并没有包含 <fstream> - Billy ONeal
我已经将它包含在我的主文件中,但没有包含在有问题的函数文件中。感谢您的帮助。 - Jesse Welch

5

看起来您的源代码中 #included <iosfwd> 被错误地使用,应该使用 <fstream>。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接