C++ C++;构造函数错误
我正在为编译器编写解析器。对于构造函数,我有以下代码:C++ C++;构造函数错误,c++,parsing,constructor,C++,Parsing,Constructor,我正在为编译器编写解析器。对于构造函数,我有以下代码: //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(
//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在解析器头中声明为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);
}
但是,这会创建一堆对词法分析器文件和函数的未定义引用!
我已经正确地包括了这些文件。但到目前为止,我不明白如何克服这个问题
更新
头文件包括:
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文件。我应该将解析器头文件包括在词法分析器头文件中吗?似乎不太可能。但我该如何应对呢 构造函数内的代码在对象已构造时运行。您的类
MyLex
没有默认构造函数。因此,您必须定义默认构造函数,否则它应该是:
//constructor
Parser::Parser(char* file): MyLex(file)
{
}
如果出现“undefined symbol”链接器错误,则忘记将一些
.cpp
文件(可能是lexy2.cpp)添加到项目或编译器命令行。假设所有未定义的符号都位于lexy2.cpp中,然后尝试g++parsy.cpp parsydriver.cpp lexy2.cpp
第二种方法是正确的方法。如果第一种方法奏效,问题仍然存在。它们是由于您没有以某种形式正确链接而产生的链接器错误。如何克服链接器错误?我将编辑并更新我把头文件包含在哪里的问题?如果是这样,在解析器之前构造Lex。如果不是派生的,那么也要先构造Lex。你说你在标题中声明了myLex。这意味着u是用默认构造函数声明的?如果是这样,这就是原因,因为您没有定义默认构造函数。尝试在头文件中声明一个指向lex的指针,而不是变量本身。我应该如何在shell中编译它?文件是:lexy2.h lexy2.cpp parsy.h parsy.cpp和parsydriver.cpp