C ++如何将父级传递给需要子级的函数?

时间:2020-02-06 03:20:38

标签: c++ pointers inheritance parent-child

我有此代码:

AST* visit(AST* node)
{
    if (node->name == "BinOp")
    {
        return visit_BinOp(node);
    }
    generic_visit(node);
    return nullptr;
}

AST是仅具有名称成员的类,默认为“未定义”。 我正在尝试将AST对象(节点)传递给visit_BinOp,它需要一个BinOp对象。 BinOp是AST的孩子。 这是visit_BinOp:

int visit_BinOp(BinOp* node)
{
    if (node->op->type == PLUS)
    {
        //code
    }
}

这给了我这个错误:

argument of type "AST *" is incompatible with parameter of type "BinOp *".

我不确定该怎么做。 “节点”是通用AST *,可以是BinOp *,也可以是AST的子类。

AST:

class AST
{
public:
    string name = "undefined";
};

BinOp:

class BinOp : public AST
{
public:
    AST* left;
    Token* op;
    AST* right;

    BinOp(AST* left, Token* op, AST* right)
    {
        this->left = left;
        this->op = op;
        this->right = right;
        name = "BinOp";
    }
};

0 个答案:

没有答案
相关问题