C ++从具有相同虚拟函数名称的多个基类继承 [英] C++ inherit from multiple base classes with the same virtual function name
问题描述
我试过这段代码:
class A
{
virtual void foo() = 0;
};
class B
{
virtual void foo() = 0;
};
class C : public A, public B
{
//virtual void A::foo(){}
//virtual void B::foo(){}
virtual void A::foo();
virtual void B::foo();
};
void C::A::foo(){}
void C::B::foo(){}
int main()
{
C c;
return 0;
}
使用注释部分时可以,但是当我尝试写定义以外的类声明,编译器报告错误。
我使用的是MSVC11编译器,有没有人知道如何写这个?
我需要将代码移动到cpp文件中。
It is OK when using the commented part, but when I try to write the definitions outside the class declaration, the compiler reports errors. I am using the MSVC11 compiler, does anyone know how to write this? I need to move the code into the cpp file.
谢谢~~
推荐答案
函数根据名称和参数类型覆盖基类的虚函数(见下文)。因此,您的类 C
有两个虚函数 foo
c $ c> A 以及 B
。但是函数 void C :: foo()
覆盖两个:
A function overrides a virtual function of a base class based on the name and parameter types (see below). Therefore, your class C
has two virtual functions foo
, one inherited from each A
and B
. But a function void C::foo()
overrides both:
.virtual] / 2
[class.virtual]/2
如果虚拟成员函数
vf
classBase
和在Derived
中直接或间接从Base
,具有相同名称,参数类型列表,cv-qualification和ref-qualifier的成员函数vf
同样)如果Base :: vf
被声明,则Derived :: vf
也是虚拟的是如此声明的),并且它覆盖Base :: vf
。
If a virtual member function
vf
is declared in a classBase
and in a classDerived
, derived directly or indirectly fromBase
, a member functionvf
with the same name, parameter-type-list, cv-qualification, and ref-qualifier (or absence of same) asBase::vf
is declared, thenDerived::vf
is also virtual (whether or not it is so declared) and it overridesBase::vf
.
正如我在评论中所说,[dcl.meaning] / 1禁止在(成员)函数的声明中使用 qualified-id :
As I already stated in the comments, [dcl.meaning]/1 forbids the use of a qualified-id in the declaration of a (member) function:
当 declarator-id 被限定时,声明将引用前面声明的类或命名空间的成员
When the declarator-id is qualified, the declaration shall refer to a previously declared member of the class or namespace to which the qualifier refers [...]"
因此任何 virtual void X :: foo();
作为 C
内的声明是非法的。
Therefore any virtual void X::foo();
is illegal as a declaration inside C
.
代码
class C : public A, public B
{
virtual void foo();
};
是AFAIK覆盖 foo
,它将覆盖 A :: foo
和 B :: foo
。没有办法对 A :: foo
和 B :: foo
有两个不同的覆盖通过引入另一层继承:
is the only way AFAIK to override foo
, and it will override both A::foo
and B::foo
. There is no way to have two different overrides for A::foo
and B::foo
with different behaviour other than by introducing another layer of inheritance:
#include <iostream>
struct A
{
virtual void foo() = 0;
};
struct B
{
virtual void foo() = 0;
};
struct CA : A
{
virtual void foo() { std::cout << "A" << std::endl; }
};
struct CB : B
{
virtual void foo() { std::cout << "B" << std::endl; }
};
struct C : CA, CB {};
int main() {
C c;
//c.foo(); // ambiguous
A& a = c;
a.foo();
B& b = c;
b.foo();
}
这篇关于C ++从具有相同虚拟函数名称的多个基类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!