【发布时间】:2020-03-20 00:09:59
【问题描述】:
对于下面的代码泛滥,我们深表歉意。第一次发帖,想详细点。
我通过将变量和方法从 main 移动到一个名为 XMLParser 的类来试验现有的、用 C++ 编写的可运行的 XML 解析器。我的目标是稍微清理一下代码,让以后的维护更容易一些。
在移动变量和方法之后,我在将缓冲区声明从 main 移动到 XMLParser.hpp 后特别遇到以下错误:
/[build directory]/XMLParser.hpp:37:30: error: ‘BUFFER_SIZE’ is not a type
std::vector<char> buffer(BUFFER_SIZE);
buffer 是一个 std::vector 容器,其大小由const int BUFFER_SIZE 声明。 BUFFER_SIZE 在refillBuffer.hpp 中声明和初始化。当buffer 在main 而不是XMLParser.hpp 中声明时,解析器运行没有问题。从main 和XMLParser.hpp 访问refillBuffer 中的BUFFER_SIZE 有什么区别导致程序出现这样的错误? XMLParser.hpp 中是否存在阻止其查看 BUFFER_SIZE 的范围问题?
main.cpp:
#include "refillBuffer.hpp"
#include "XMLParser.hpp"
int main() {
XMLParser parser;
// std::vector<char> buffer(BUFFER_SIZE);
// auto pc = buffer.cend();
while (true) {
// parse XML using methods and variables in parser
}
// print report here
return 0;
}
XMLParser.hpp
#ifndef INCLUDE_XMLPARSER_HPP
#define INCLUDE_XMLPARSER_HPP
#include "refillBuffer.hpp"
#include <vector>
#include <errno.h>
#include <stdlib.h>
#include <algorithm>
#include <cstring>
#include <iostream>
class XMLParser {
public:
int textsize = 0;
int loc = 0;
int expr_count = 0;
int function_count = 0;
int class_count = 0;
int file_count = 0;
int decl_count = 0;
int comment_count = 0;
int return_count = 0;
int literal_string_count = 0;
int block_comment_count = 0;
int depth = 0;
long total = 0;
bool intag = false;
std::vector<char> buffer(BUFFER_SIZE);
auto pc = buffer.cend();
// methods using above variables go here
};
#endif
refillBuffer.hpp
#ifndef INCLUDE_REFILLBUFFER_HPP
#define INCLUDE_REFILLBUFFER_HPP
#include <vector>
#include <iterator>
const int BUFFER_SIZE = 16 * 4096;
// Refill the buffer preserving the unused data
std::vector<char>::const_iterator refillBuffer(std::vector<char>::const_iterator pc, std::vector<char>& buffer, long& total);
#endif
'''
【问题讨论】: