簡體   English   中英

在 C++ 中使用 inheritance 的編譯器錯誤

[英]Compiler errors using inheritance in C++

我是 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'

據我了解,編譯器無法編譯此代碼,因為 class QuantifiableNodeImpl繼承 class NodeBase和接口QuantifiableNode兩者都有一個方法MatchNodeBaseNode實現它, QuantifiableNodeNode繼承抽象方法)。 我需要同時擁有NodeQuantifiableNode這兩個接口,並在另一個代碼中使用它們。 此外,我需要有NodeBase class 以分離基本功能(在我的真實代碼中,我有許多NodeBase的衍生物)。

此外,class QuantifiableNodeImpl的 object 也無法創建,編譯器說它有一個未實現的抽象Match方法。

所以我該怎么做? 希望得到您的幫助!

看來您對鑽石 inheritance 並不完全熟悉。 QuantifiableNodeImpl有兩個Node子對象,一個通過NodeBase ,一個通過QuantifiableNode 第二個Node子對象缺少QuantifiableNode::Match

看起來這可能不是故意的: QuantifiableNode真的應該是一個Node本身嗎? QuantifiableNode::Match應該如何工作?

可能是Quantifiable更准確地建模為mixin

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM