[英]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
兩者都有一個方法Match
( NodeBase
從Node
實現它, QuantifiableNode
從Node
繼承抽象方法)。 我需要同時擁有Node
和QuantifiableNode
這兩個接口,並在另一個代碼中使用它們。 此外,我需要有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.