无法转换某些 类 但其他可以。 C++

Cannot convert some classes but others can. C++

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

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

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

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

这些是 classes 定义:

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

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

您不能将 class 的实例转换为指向实例的指针。请注意错误消息中的 *

在有效的规则中,您将 $$ 设置为 new NIdentifier,这是一个指向新实例的指针。

如@md5i 所述,我没有使用 new 创建 NInteger 实例,因此堆中没有对象可供引用。这是通过在 NInteger.

前面添加 new 运算符来解决的
ident : TIDENTIFIER { $$ = new NIdentifier(*); delete ; }
  ;
numeric : TINTEGER { $$ = NInteger(atol(->c_str())); delete ; }
  ;

你忘了把 new NInteger 放在第一行。