C++ 从多个具有相同虚函数名称的基类继承
我试过这个代码:
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
,一个从A
和B代码>.但是一个函数
void C::foo()
覆盖了 both:
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:
[class.virtual]/2
[class.virtual]/2
如果在类Base
和类Derived
中声明了虚拟成员函数vf
,直接或间接从派生Base
,一个成员函数vf
,同名,parameter-type-list,cv-qualification,和ref-qualifier(或没有相同的)作为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();
}
相关文章