我试过这段代码:
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 文件中。
谢谢~~
最佳答案
函数根据名称和参数类型覆盖基类的虚函数(见下文)。因此,你的类 C
有 两个 虚函数 foo
,一个继承自 A
和 B
。但是函数 void C::foo()
会覆盖 both:
[class.virtual]/2
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:
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
中的声明都是非法的。
代码
class C : public A, public B
{
virtual void foo();
};
是 AFAIK 覆盖 foo
的唯一方法,它将覆盖 A::foo
和 B::foo
。除了引入另一层继承之外,没有办法对 A::foo
和 B::foo
进行两种不同的覆盖:
#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++从多个具有相同虚函数名的基类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18398409/