在 C++ 中使用继承的编译器错误

禅诺2

我是 C++ 的新手。我编写了一个示例代码来说明问题并导致编译器错误。

class Quantifier;

class Node {
public:
    virtual void Match(/* args */) = 0;
};

class QuantifiableNode : public Node {
public:
    virtual void SetQuantifier(Quantifier *quantifier) = 0;
};

class NodeBase : public Node {
public:
    void Match() override {
        // Base behavior
    }
};

class QuantifiableNodeImpl : public NodeBase, // Needed to inherit base behavior
                             public QuantifiableNode // Needed to implement QuantifiableNode interface
{
public:
    void SetQuantifier(Quantifier *quantifier) override {}

    void Method() {
        this->Match();
    }
};

int main() {
    QuantifiableNodeImpl node;
    node.Match();
    return 0;
}

我收到这些错误:

main.cpp(27): error C2385: ambiguous access of 'Match'
main.cpp(27): note: could be the 'Match' in base 'NodeBase'
main.cpp(27): note: or could be the 'Match' in base 'Node'
main.cpp(32): error C2259: 'QuantifiableNodeImpl': cannot instantiate abstract class
main.cpp(20): note: see declaration of 'QuantifiableNodeImpl'
main.cpp(32): note: due to following members:
main.cpp(32): note: 'void Node::Match(void)': is abstract
main.cpp(5): note: see declaration of 'Node::Match'
main.cpp(33): error C2385: ambiguous access of 'Match'
main.cpp(33): note: could be the 'Match' in base 'NodeBase'
main.cpp(33): note: or could be the 'Match' in base 'Node'

据我理解,因为类编译器不能编译此代码QuantifiableNodeImpl继承类NodeBase和接口QuantifiableNode,其都具有方法MatchNodeBase实现它从NodeQuantifiableNode从继承抽象方法Node)。我需要同时拥有这两个接口NodeQuantifiableNode在另一个代码中使用它们。另外,我需要有NodeBase类来分离基本功能(在我的真实代码中,我有许多 的派生类NodeBase)。

另外,QuantifiableNodeImpl也不能创建类的对象,编译器说它有一个未实现的抽象Match方法。

所以我该怎么做?希望得到您的帮助!

MSalters

看来您对钻石继承并不完全熟悉。QuantifiableNodeImpl有两个Node子对象,一个 viaNodeBase和一个 via QuantifiableNode第二Node个子对象缺少QuantifiableNode::Match.

似乎这可能不是故意的:它本身就QuantifiableNode应该是 aNode吗?QuantifiableNode::Match应该如何工作?

可能Quantifiable更准确地建模为mixin

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章