C++ inherit from multiple base classes with the same virtual function name

前端 未结 4 1937
自闭症患者
自闭症患者 2020-11-28 16:47

I tried this code:

class A
{
    virtual void foo() = 0;
};

class B
{
    virtual void foo() = 0;
};

class C : public A, public B
{
    //virtual void A::f         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 16:57

    You can resolve this ambiguity with different function parameters.

    In real-world code, such virtual functions do something, so they usually already have either:

    1. different parameters in A and B, or
    2. different return values in A and B that you can turn into [out] parameters for the sake of solving this inheritance problem; otherwise
    3. you need to add some tag parameters, which the optimizer will throw away.

    (In my own code I usually find myself in case (1), sometimes in (2), never so far in (3).)

    Your example is case (3) and would look like this:

    class A
    {
    public:
        struct tag_a { };
        virtual void foo(tag_a) = 0;
    };
    
    class B
    {
    public:
        struct tag_b { };
        virtual void foo(tag_b) = 0;
    };
    
    class C : public A, public B
    {
        void foo(tag_a) override;
        void foo(tag_b) override;
    };
    

提交回复
热议问题