c++ - 错误 : invalid declarator before ‘&’ token

标签 c++ stl compiler-errors g++ syntax-error

我正在尝试编写一个允许用户的 TextQuery 程序:
1. 输入一个词
2. 读取文件
3. 打印出单词出现在哪几行以及单词在该行出现了多少次

我创建了一个名为 "TextQuery" 的类,其中包含 3 个成员函数:
1. “read_file”读取文件并返回对 vector 的引用
2. "find_word"取需要查找的词
然后返回对 ma​​p< int, pair >
的引用 (第一个 'int' 是行号,第二个 'int' 是单词在该行出现的次数,'string' 是整行)
3. "write_out"写入结果。

但是,当我编译程序时,我收到了这条消息:

/home/phongcao/C++/textquery_class_1.cc:21: error: invalid declarator before ‘&’ token


我只是想知道声明者怎么会错?这是类定义部分:

#include <iostream>
#include <fstream>
#include <algorithm>
#include <map>
#include <vector>
#include <string>

using namespace std;

class TextQuery {
public:
  vector<string> &read_file(ifstream &infile) const;
  map< int, pair<string, int> > &find_word(const string &word) const;  
  void write_out(const string &word) const;

private:
  vector<string> svec;
  map< int, pair<string, int> > result;
}

//The following line is line 21, where I got the error!!
vector<string> &TextQuery::read_file(ifstream &infile) const {
  while (getline(infile, line)) {
    svec.push_back(line);
  }
  return svec;
}

map< int, pair<string, int> > &TextQuery::find_word(const string &word) const {
  for (vector<string>::size_type i = 0; i != svec.end()-1; ++i) {
    int rep_per_line = 0;
    pos = svec[i].find(word, 0);
    while (pos != string::npos) {
      if (!result[i+1]) {
        result.insert(make_pair(i+1, make_pair(svec[i], rep_per_line)));
        ++result[i+1].second;
      }
      else {
        ++result[i+1].second;
      }
    }
  }
  return result;
}

void TextQuery::write_out(const string &word) {
  cout << " The word " << "'" << word << "'" << " repeats:" << endl;
  for (map< int, pair<string, int> >::const_iterator iter = result.begin(); iter != result.end(); ++iter) {
    cout << "(line " << (*iter).first << " - " << (*iter).second.second << " times): ";
    cout << result.second.first << endl; 
  }
}



这是程序的其余部分:

int main() 
{
  string word, ifile;
  TextQuery tq;  

  cout << "Type in the file name: " << endl;
  cin >> ifile;

  ifstream infile(ifile.c_str());

  tq.read_file(infile);

  cout << "Type in the word want to search: " << endl;
  cin >> word;

  tq.find_word(word);
  tq.write_out(word);

  return 0;
}


谢谢你回答我的问题!!

最佳答案

类定义后缺少;

为什么会出现奇怪的错误消息?因为在该范围级别创建对象是完全合法的:

class ABC {
...
} globalABC;

关于c++ - 错误 : invalid declarator before ‘&’ token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5519343/

相关文章:

c++ - 为什么同样的代码通过gcc可以编译成功,而g++却不行?

iphone - objective-c : strange error when init a variable declared in my header file

compiler-errors - Swift 3编译错误。无法将type()转换为int类型

C++ 文件处理:ios::ate 无法正常工作

c++ - C++ 中的简单多线程服务器?

c++ - std::unordered_multimap 中元素的顺序

c++ - 如何将自定义对象插入到 std::map 中?

c++ - 如何获得物体的距离以及如何正确使用相机校准矩阵?

c++ - 我如何让这个 C++ 计算程序留在控制台上?

c++ - 无符号字符数组以键入 STL::map 或其他容器