我对vector的所有命名空间以及如何在我的类中正确返回字符串向量感到困惑。这是代码:
的main.cpp
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <string>
#include "lab1.h"
using namespace std;
readwords wordsinfile;
words wordslist;
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) {
// Looks like we have no arguments and need do something about it
// Lets tell the user
cout << "Usage: " << argv[0] <<" <filename>\n";
exit(1);
} else {
// Yeah we have arguements so lets make sure the file exists and it is readable
ifstream ourfile(argv[1]);
if (!ourfile.is_open()) {
// Then we have a problem opening the file
// Lets tell the user and exit
cout << "Error: " << argv[0] << " could not open the file. Exiting\n";
exit (1);
}
// Do we have a ASCII file?
if (isasciifile(ourfile)) {
cout << "Error: " << argv[0] << " only can handle ASCII or non empty files. Exiting\n";
exit(1);
}
// Let ensure we are at the start of the file
ourfile.seekg (0, ios::beg);
// Now lets close it up
ourfile.close();
}
// Ok looks like we have past our tests
// Time to go to work on the file
ifstream ourfile2(argv[1]);
wordsinfile.getwords(ourfile2);
lab1.h
#ifndef LAB1_H
#define LAB1_H
bool isasciifile(std::istream& file);
class readwords {
public:
int countwords(std::istream& file);
std::vector<std::string> getwords(std::istream& file);
};
class words {
public:
void countall( void );
void print( void );
};
#endif
lab1.cpp
#include <fstream>
#include <iostream>
#include <map>
#include "lab1.h"
#include <vector>
using std::vector;
#include <string>
using namespace std;
vector<string> readwords::getwords(std::istream& file) {
char c;
string aword;
vector<string> sv;
int i = 0;
while(file.good()) {
c = file.get();
if (isalnum(c)) {
if(isupper(c)) {
c = (tolower(c));
}
if(isspace(c)) { continue; }
aword.insert(aword.end(),c);
} else {
if (aword != "") {sv.push_back(aword);}
aword = "";
i++;
continue;
}
}
return sv;
}
以下是编译时的错误。
g++ -g -o lab1 -Wall -pedantic main.cpp lab1.cpp
In file included from lab1.cpp:4:0:
lab1.h:9:4: error: ‘vector’ in namespace ‘std’ does not name a type
lab1.cpp:48:54: error: no ‘std::vector<std::basic_string<char> > readwords::getwords(std::istream&)’ member function declared in class ‘readwords’
make: *** [lab1] Error 1
为什么我会收到此错误以及如何解决此问题。感谢您提供的任何帮助。
赖安
答案 0 :(得分:5)
您还必须在头文件中#include <vector>
。实际上,将它包含在标题中就足够了,因为包含该标题的所有文件都将隐含地包含<vector>
。
事情是你的包含顺序是:
#include "lab1.h"
#include <vector>
并且由于您在标题中使用std::vector
(在包含它之前),您会收到错误消息。反转包含顺序将修复编译错误,但不解决基础错误 - lab1
使用尚未定义的符号。正确的解决方法是包含<vector>
。
答案 1 :(得分:1)
编译器按照编写的顺序查看代码。这也适用于#include指令:文件的内容被视为已经写入#include它们的文件中。正如@LuchianGrigore所提到的,最好的解决方案是添加
#include <vector>
到“lab1.h”。但是你可以通过移动“{1}} in”lab1.cpp“来隐藏问题,使它在#include <vector>
之前开始读取”lab1.h“之前。这不是你应该做的,但这是偶然发生的事情并隐藏实际问题。