164

对不起,如果这很无聊,但我对 C++ 很陌生。我正在尝试打开一个文件并使用ifstream

vector<string> load_f(string file) {
  vector<string> text;

  ifstream ifs(file);
  string buffer, str_line;

  int brackets = 0;
  str_line = "";

  while ( getline(ifs, buffer) ) {
    buffer = Trim( buffer );
    size_t s = buffer.find_first_of("()");

    if (s == string::npos) str_line += "" + buffer;
    else {
      while ( s != string::npos ) {
        str_line += "" + buffer.substr(0, s + 1);
        brackets += (buffer[s] == '(' ? 1 : -1);

        if ( brackets == 0 ) {
          text.push_back( str_line );
          str_line = "";
        }

        buffer = buffer.substr(s + 1);
        s = buffer.find_first_of("()");
      }
    }
  }

  return text;
}

但是,我收到以下错误,我不太确定如何解决:

variable 'std::ifstream ifs' has initializer but incomplete type

答案非常感谢。请注意,我从来没有忘记#include <fstream>,因为许多人因为忘记包含标题而得到错误。

编辑:

原来我确实忘记了 include fstream,但由于将函数移动到另一个文件而我忘记了。

4

1 回答 1

138

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

于 2015-09-18T14:26:02.867 回答