C++ 构造函数错误

标签 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()’
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 header 中被声明为 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);
}

但是,这会创建一堆对词法分析器文件和函数的 undefined reference ! 我已经正确地包含了这些文件。但到目前为止,我不明白如何解决这个问题。

更新 头文件包括:

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)添加到项目或编译器命令行。假设所有 undefined symbol 都位于 lexy2.cpp 中,然后尝试 g++ parsy.cpp parsydriver.cpp lexy2.cpp

关于C++ 构造函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15081393/

相关文章:

c++ - 我需要帮助来理解如何找到代码段的 Big-Oh

c++ - 查找 cv::Mat 的最大值

c++ - 期望标题中的参数

java - 使用 SGML 解析 Java 字符串

C++多维 vector

javascript - Jquery 平滑滚动到 DIV - 使用链接中的 ID 值

javascript - 在 Nodejs 中解析大型 JSON 文件并独立处理每个对象

java 和继承构造函数

c# - 为什么不能在另一个构造函数的主体中访问构造函数?

c++ - 类组合 - 无法从 'int' 转换为类