我正在为编译器编写解析器。所以对于构造函数我有代码:
//constructor
Parser::Parser(char* file)
{
MyLex(file) ;
}
使用 g ++ parsy.cpp parsydriver.cpp 编译时,我收到此错误说:
parsy.cpp: In constructor ‘Parser::Parser(char*)’:
parsy.cpp:13: error: no matching function for call to ‘Lex::Lex()’
lexy2.h:34: note: candidates are: Lex::Lex(char*)
lexy2.h:31: note: Lex::Lex(const Lex&)
parsy.cpp:15: error: no match for call to ‘(Lex) (char*&)’
我哪里错了? Lex myLex 在Parser标头中声明为私有。我没办法 。我试过用这个:
//constructor
Parser::Parser(char* file):myLex(file)
{
}
我的词法分析器构造函数是:
Lex::Lex(char* filename): ch(0)
{
//Set up the list of reserved words
reswords[begint] = "BEGIN";
reswords[programt] = "PROGRAM";
reswords[constt] = "CONST";
reswords[vart] = "VAR";
reswords[proceduret] = "PROCEDURE";
reswords[ift] = "IF";
reswords[whilet] = "WHILE";
reswords[thent] = "THEN";
reswords[elset] = "ELSE";
reswords[realt] = "REAL";
reswords[integert] = "INTEGER";
reswords[chart] = "CHAR";
reswords[arrayt] = "ARRAY";
reswords[endt] = "END";
//Open the file for reading
file.open(filename);
}
但是,这会创建一堆对Lexical Analyzer文件和函数的未定义引用! 我已正确包含文件。但到目前为止,我不明白如何克服这个问题。
更新 头文件包含是:
parsy.h文件:
#ifndef PARSER_H
#define PARSER_H
// other library file includes
#include "lexy2.h"
class Parser
{
}...
parsy.cpp文件:
// usual ilbraries
#include "parsy.h"
using namespace std ;
Parser::Parser(char* file) ....
parsydriver.cpp:
// usual libraries
#include "parsy.h"
using namespace std ;
int main()
..
lexy2.cpp文件:
我已经包含了lexy2.h文件。我应该在词法分析器中包含解析器头文件吗?似乎不太可能。但是我该怎样解决它们呢?
答案 0 :(得分:2)
构造函数内部的代码在已构造对象时运行。您的班级MyLex
没有默认构造函数。所以你必须定义默认构造函数,或者它应该是:
//constructor
Parser::Parser(char* file): MyLex(file)
{
}
如果您有“未定义的符号”链接器错误,那么您忘记将一些.cpp
文件(可能是lexy2.cpp)添加到项目或编译器命令行。假设所有未定义的符号都位于lexy2.cpp中,那么请尝试g++ parsy.cpp parsydriver.cpp lexy2.cpp
。