在标头中添加typedef时出错



我是C++的新手,正在学习Accelerated C++(对于任何有这本书的人来说,我正在尝试运行§7.4中描述的程序)

我正在看的程序使用了一些typedef——我估计,如果我将这些添加到头文件中,任何包含该头的源文件都可以使用typedef。

我的标题是:

#ifndef READ_GRAMMAR_H_INCLUDED
#define READ_GRAMMAR_H_INCLUDED
typedef std::vector<std::string> Rule;
typedef std::vector<Rule> Rule_collection;
typedef std::map<std::string, Rule_collection> Grammar;
Grammar read_grammar(std::istream& in);
#endif // READ_GRAMMAR_H_INCLUDED

这给了我错误error: 'map' in namespace 'std' does not name a type

如果我将第三个typedef更改为typedef std::vector<Rule_collection> Grammar;(这并不是我想要的,只是举个例子),它就不会出错。

知道问题出在哪里吗?我不知道我是在用错误的方式做一些琐碎的事情,还是整个方法是不正确的

它说在名称空间std中找不到map。您需要包含它,以便编译器能够找到它。同样,您需要包含std::vectorstd::stringstd::istream:的标头

#ifndef READ_GRAMMAR_H_INCLUDED
#define READ_GRAMMAR_H_INCLUDED
#include <map>
#include <vector>
#include <string>
#include <istream>
typedef std::vector<std::string> Rule;
typedef std::vector<Rule> Rule_collection;
typedef std::map<std::string, Rule_collection> Grammar;
Grammar read_grammar(std::istream& in);
#endif // READ_GRAMMAR_H_INCLUDED

如果你觉得有勇气,你可能还想阅读转发声明——它们的用法、优点和缺点,但我怀疑在这种特殊情况下是否需要它。

必须包含头文件,如果没有,程序将如何使用它?

#ifndef READ_GRAMMAR_H_INCLUDED
#define READ_GRAMMAR_H_INCLUDED
#include <istream>
#include <string>
#include <vector>
#include <map>
typedef std::vector<std::string> Rule;
typedef std::vector<Rule> Rule_collection;
typedef std::map<std::string, Rule_collection> Grammar;
Grammar read_grammar(std::istream& in);
#endif // READ_GRAMMAR_H_INCLUDED

最新更新