如何在多重继承中实现具有相同名称的虚函数 [英] How to implement virtual functions with the same name in multiple inheritance
问题描述
有如下代码
// 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()实现。
Note that there is a default implementation of F() in the base classes.
感谢Jan Herrmann和Spook。下面是一个更简单的解决方案,如果我们必须使用一些额外的帮助?
Thanks to Jan Herrmann and Spook. Is the below a simpler solution if we have to use some extra helpers?
#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;
}
推荐答案
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() { ... }
};
如果我记得正确,ISO委员会想到了这个问题,并讨论了语言的变化。但是...有人发现这个很好的方法来解决这个问题: - )
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 :-)
你的第二个解决方案是更好的,如果你能够改变你的类层次结构。您可能在 http://www.gotw.ca/publications/mill18.htm上有锁a>为什么它更好的描述。
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.
这篇关于如何在多重继承中实现具有相同名称的虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!