0

我正在为编译器编写解析器。所以对于构造函数我有代码:

//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);
}

但是,这会创建一堆对词法分析器文件和函数的未定义引用!我已正确包含文件。但到目前为止,我不明白如何克服这个问题。

更新 头文件包含:

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 文件。我应该在词法分析器中包含解析器头文件吗?似乎不太可能。但是我应该如何解决它们呢?

4

1 回答 1

2

构造函数内的代码在对象已经构造时运行。您的类MyLex没有默认构造函数。所以你必须定义默认构造函数或者它应该是:

//constructor
Parser::Parser(char* file): MyLex(file)
{
}

如果您有“未定义符号”链接器错误,那么您忘记将一些.cpp文件(可能是 lexy2.cpp)添加到项目或编译器命令行。假设所有未定义的符号位于 lexy2.cpp 然后尝试g++ parsy.cpp parsydriver.cpp lexy2.cpp.

于 2013-02-26T04:49:34.873 回答