简体   繁体   中英

Compiler errors using inheritance in C++

I'm a newbie in C++. I've written an example code that illustrates the problem and causes compiler errors.

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

I get these errors:

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'

As far as I understand, the compiler can't compile this code because class QuantifiableNodeImpl inherits class NodeBase and interface QuantifiableNode which both have a method Match ( NodeBase implements it from Node , QuantifiableNode inherits abstract method from Node ). I need to have both of the interfaces Node and QuantifiableNode and use them in another code. Also, I need to have NodeBase class in order to separate base functionality (in my real code I have many derivatives of NodeBase ).

Also, an object of class QuantifiableNodeImpl can't be created too, the compiler says that it has an unimplemented abstract Match method.

So, what should I do? Hope for your help!

It seems you're not entirely familiar with diamond inheritance. QuantifiableNodeImpl has two Node sub-objects, one via NodeBase and one via QuantifiableNode . The second Node subobject lacks a QuantifiableNode::Match .

It seems that this might not be intentional: is QuantifiableNode really supposed to be a Node in its own right? How is QuantifiableNode::Match supposed to work?

It might be that Quantifiable is more accurately modelled as a mixin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM