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文件中.
谢谢~~
解决方法
[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 […]”
因此任何虚拟的空虚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(); }