覆盖合格的虚拟方法 [英] Overriding Qualified Virtual Methods
问题描述
我有多个父级的 C++ 类;每个父级都定义了一个具有通用名称但用途不同的函数:
I have C++ class with multiple parents; each parent defines a function with a common name but a different purpose:
class BaseA
{
virtual void myFunc(); // does some task
};
class BaseB
{
virtual void myFunc(); // does some other task
};
class Derived : public BaseA, public BaseB;
如果是这样,我就没有问题 - 我可以用 using 语句解决歧义,我可以选择使用基类名称和范围解析运算符调用哪个.
If that was it, I would have no problem - I could resolve the ambiguity it with a using statement, and I could choose which one to call using the base class names and the scope resolution operator.
不幸的是,派生类需要覆盖它们:
Unfortunately, the derived class needs to override them both:
class Derived : public BaseA, public BaseB
{
virtual void BaseA::myFunc(); // Derived needs to change the way both tasks are done
virtual void BaseB::myFunc();
}
这不起作用,不是因为它引入了新的歧义(尽管可能),而是因为
This doesn't work, not because it introduces a new ambiguity (although it may), but because
错误 C3240: 'myFunc' : 必须是 'BaseA' 的非重载抽象成员函数"
"error C3240: 'myFunc' : must be a non-overloaded abstract member function of 'BaseA'"
错误 C2838:成员声明中的限定名非法"
"error C2838: illegal qualified name in member declaration"
在不同的情况下,我可能只是重命名方法,或者按照编译器的建议使它们纯虚拟.但是,类层次结构和许多外部问题使第一个选项极其困难,而第二个选项则不可能.
Under different circumstances I might just rename the methods, or make them pure virtual as the compiler suggests. However, the class hierarchy structure and a number of external issues make the first option extremely difficult, and the second impossible.
有人有什么建议吗?为什么限定符只允许用于纯虚方法?有没有办法同时覆盖虚方法和解决歧义?
Does anyone have a suggestion? Why are qualifiers only allowed for pure virtual methods? Is there any way to simultaneously override virtual methods and resolve ambiguities?
推荐答案
Microsoft 允许该语法(从 Visual C++ 2005 开始可用).他们还为托管代码引入了一种新的、更强大的语法.
Microsoft allows that syntax (it's available beginning in Visual C++ 2005). They also introduced a new, more powerful syntax for managed code only.
C++0x 中没有一个.
Neither one was included in C++0x.
参见 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2108.html
我认为这是一种解决方法:
I think this is a workaround:
class BaseA
{
protected:
virtual void myFunc(); // does some task
};
class BaseB
{
protected:
virtual void myFunc(); // does some other task
};
class ShimA : virtual BaseA
{
virtual void myFunc() { myFuncA(); }
protected:
virtual void myFuncA() { BaseA::myFunc(); }
};
class ShimB : virtual BaseB
{
virtual void myFunc() { myFuncB(); }
protected:
virtual void myFuncB() { BaseB::myFunc(); }
};
class Derived : public virtual BaseA, public virtual BaseB, protected ShimA, protected ShimB
{
virtual void myFuncA() {}
virtual void myFuncB() {}
};
这篇关于覆盖合格的虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!