不能转换某些类,但其他人可以。 C ++

时间:2016-06-08 16:08:18

标签: c++ oop compiler-errors bison

我在parser.y中有这些规则:

ident : TIDENTIFIER { $$ = new NIdentifier(*$1); delete $1; }
  ;
numeric : TINTEGER { $$ = NInteger(atol($1->c_str())); delete $1; }
  ;

当我使用g++ -o parser parser.y tokens.flex main.cpp编译时,我得到:

parser.y:82:63: error: cannot convert ‘NInteger’ to ‘NExpression*’ in assignment
TINTEGER { $$ = NInteger(atol($1->c_str())); delete $1; }
                                                 ^

这些是类定义:

class Node {
public:
  virtual ~Node() {}
};

class NExpression : public Node {
};

class NInteger : public NExpression {
public:
  long long value;
  NInteger(long long value) : value(value) { }
};

class NIdentifier : public NExpression {
public:
  std::string name;
  NIdentifier(const std::string& name) : name(name) { }
};

我不明白为什么一个类可以转换而另一个类不能转换,因为两个类都继承自同一个父级,并且两个构造函数具有相同的机制。

3 个答案:

答案 0 :(得分:2)

您无法将类的实例转换为指向实例的指针。请注意错误消息中的*

在适用的规则中,您将$$设置为new NIdentifier,这是指向新实例的指针。

答案 1 :(得分:1)

ident : TIDENTIFIER { $$ = new NIdentifier(*$1); delete $1; }
  ;
numeric : TINTEGER { $$ = NInteger(atol($1->c_str())); delete $1; }
  ;

您忘记在第一行添加new NInteger

答案 2 :(得分:0)

正如@ md5i所述,我没有使用NInteger创建new实例,因此堆中没有对象可供引用。通过在new前添加NInteger运算符来解决此问题。

相关问题