假设有这个接口(interface):
class A{
public:
virtual foo()=0;
};
还有一个类 B
实现了这个接口(interface):
class B:public A{
public:
virtual foo(){} //Foo implemented by B
}
最后,一个 C
类,它有 A
和 B
作为基类:
Class C : public A, public B {
};
我的问题是,有一种方法可以告诉编译器 foo
的实现是来自类 B
的实现,而无需显式调用 B::foo()
?
最佳答案
正如@BenVoigt 在评论中指出的那样,以下答案仅适用于 g++ 中的错误(这意味着它不能保证继续工作,而且绝对不可移植)。因此,尽管如果您使用特定的(有问题的)编译器它可能会执行您想要的操作,但它不是您应该使用的选项。
请使用 virtual inheritance尽管。
这不完全是问题中的代码所暗示的场景,而是句子
My question is, there is a way to tell the compiler that the implementation for foo is the one from class B without doing an explicit call to B::foo()?
似乎要求语法在不使用 ::
限定符的情况下区分函数的多个基本版本。
您可以使用 using
指令执行此操作:
#include <iostream>
class A {
public:
A(){}
virtual void foo(){std::cout<<"A func";}
};
class B: virtual public A {
public:
B(){}
virtual void foo(){std::cout<<"B func";}
};
class C:virtual public A, virtual public B {
public:
C(){}
using A::foo; // tells the compiler which version to use
// could also say using B::foo, though this is unnecessary
};
int main() {
C c;
c.foo(); // prints "A func"
return 0;
}
当然,正如其他答案所指出的,问题中的代码本身根本不需要这样做。
关于c++ - 实现具有多重继承的纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14044222/