How to implement virtual functions with the same name in multiple inheritance [duplicate]

半城伤御伤魂 提交于 2019-12-03 16:13:34
class C_a 
  : public A
{
  virtual void F_A() = 0;
  virtual void F() { this->F_A() };
};

class C_b
  : public B
{
  virtual void F_B() = 0;
  virtual void F() { this->F_B() };
};

class C
  : public C_a
  , public C_b
{
  void F_A() { ... }
  void F_B() { ... }
};

If I'm remembing right the ISO committee thought about this problem and discussed a change of the language. But then ... somebody found this nice way to solve this problem :-)

Your second solution is better in case your are able to change your class hierarchy. You may have a lock at http://www.gotw.ca/publications/mill18.htm for a description why it is better.

Try this:

#include <cstdio>

class A
{
public:
    virtual void F() = 0;
};

class B
{
public:
    virtual void F() = 0;
};

class C : public A, public B
{
    void A::F()
    {
        printf("A::F called!\n");
    }

    void B::F()
    {
        printf("B::F called!\n");
    }
};

int main(int argc, char * argv[])
{
    C c;
    ((A*)(&c))->F();
    ((B*)(&c))->F();

    getchar();

    return 0;
}

Take into consideration though, that you won't be able to call F from C's instance (ambiguous call).

Also, F has to be abstract in A and B, otherwise you'll get compilation error:

Error 1 error C3240: 'F' : must be a non-overloaded abstract member function of 'A'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!