2013-02-26 174 views
0

我正在为编译器编写解析器。所以对于构造我的代码:C++构造函数错误

//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头文件中声明为private。我不知道该怎么做 。我尝试使用这样的:

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

但是,这产生了以词法分析器文件和功能一堆不确定的参考! 我已经正确地包含了这些文件。但到目前为止,我不明白如何解决这个问题。

UPDATE 头文件夹杂物:

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

+3

第二种方法是正确的方法。第一次工作时问题依然存在。他们是从你身上发芽的链接器错误,没有以某种形式正确链接。 – chris 2013-02-26 04:34:26

+0

如何克服链接器错误?我将编辑并更新我将头文件包含在内的问题。 – thestralFeather7 2013-02-26 04:35:35

+0

请选择:http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix – chris 2013-02-26 04:37:18

回答

2

构造函数中的代码在构造对象时运行。你的班级MyLex没有默认构造函数。所以,你必须定义默认构造函数,或者它应该是:

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

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

+0

好吧,我有4个文件+ 1驱动程序文件。我应该如何在shell中编译它? 文件是:lexy2。h lexy2.cpp parsy.h parsy.cpp和parsydriver.cpp – thestralFeather7 2013-02-26 04:59:47

+0

@ novice7编辑答案以添加命令行示例。 – Sergey 2013-02-26 05:04:14