有如下代码
// A has a virtual function F().
class A
{
public:
virtual void F() {};
};
// The same for B.
class B
{
public:
virtual void F() {};
};
// C inherits A and B.
class C : public A, public B
{
public:
// How to implement the 2 virtual functions with the same name but from
// different base classes.
virtual F() {...}
};
请注意,基类中有 F() 的默认实现。
感谢 Jan Herrmann 和 Spook。如果我们必须使用一些额外的助手,下面是一个更简单的解决方案吗?
#include <iostream>
// A has a virtual function F().
class A
{
private:
virtual void A_F() {}
public:
void F() {return A_F();};
};
// The same for B.
class B
{
private:
virtual void B_F() {}
public:
void F() {return B_F();};
};
// C inherits A and B.
class C : public A, public B
{
private:
virtual void A_F() {std::cout << "for A\n";}
virtual void B_F() {std::cout << "for B\n";}
};
int main()
{
C c;
c.A::F();
c.B::F();
return 0;
}