本文介绍了C ++从具有相同虚拟函数名称的多个基类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我试过这段代码: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正如我在评论中所说,[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:因此任何 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();}; $ b 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 to 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 ++从具有相同虚拟函数名称的多个基类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-22 20:22