pho*_*cao 6 c++ stl compiler-errors g++ syntax-error
我试图写一个允许用户使用的TextQuery程序:
1.输入一个单词
2. 读取文件
3. 打印出单词出现的行数和单词出现在该行上的次数.
我创建了一个名为"TextQuery"的类,其中包含3个成员函数:
1."read_file"用于读取文件并返回对向量的引用
2. "find_word"用于获取需要搜索的单词
然后返回对地图 的引用< int,pair>
(第一个'int'是行号,第二个'int'是单词出现在该行上的次数,'string'是整行)
3."write_out"写入结果.
但是,当我编译程序时,我收到了这条消息:
/home/phongcao/C++/textquery_class_1.cc:21: error: invalid declarator before ‘&’ token
Run Code Online (Sandbox Code Playgroud)
我只是想知道声明者怎么错?这是类定义部分:
#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;
}
}
Run Code Online (Sandbox Code Playgroud)
以下是该计划的其余部分:
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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢你回答我的问题!!
And*_*adt 21
;在课程定义后丢失.
为什么奇怪的错误信息?因为在该范围级别创建对象是完全合法的:
class ABC {
...
} globalABC;
Run Code Online (Sandbox Code Playgroud)