C ++:使用基类作为接口的实现 [英] C++: using a base class as the implementation of an interface
问题描述
在C ++中,是否可以使用另一个基类来提供派生类中的接口(即抽象基类)的实现?
In C++ is it possible to use another base class to provide the implementation of an interface (i.e. abstract base class) in a derived class?
class Base
{
virtual void myfunction() {/*...*/};
}
class Interface
{
virtual void myfunction() = 0;
}
class Derived
: public Base, public Interface
{
// myfunction is implemented by base
}
上面应该编译,但实际上不工作。有什么办法实现这种效果吗?
The above should compile, but doesn't actually work. Is there any way to achieve this effect?
如果任何人关心,想要这一点的原因是(使我的应用程序)使用通用库另一个项目/命名空间提供在我的项目中实现一个接口。我可以只是包装一切,但这似乎很多额外的开销。
In case anyone cares, the reason for wanting this is that it make sense (for my application) to use a generic library from another project/namespace to provide the implementation of an interface in my project. I could just wrap everything, but that seems like a lot of extra overhead.
谢谢。
推荐答案
如果 Base
不是从接口
派生的,在派生
中转发呼叫。它只是开销的意义上,你必须编写额外的代码。我怀疑优化器会像你原来的想法一样有效。
If Base
isn't derived from Interface
, then you'll have to have forwarding calls in Derived
. It's only "overhead" in the sense that you have to write extra code. I suspect the optimizer will make it as efficient as if your original idea had worked.
class Interface {
public:
virtual void myfunction() = 0;
};
class Base {
public:
virtual void myfunction() {/*...*/}
};
class Derived : public Interface, public Base {
public:
void myfunction() { Base::myfunction(); } // forwarding call
};
int main() {
Derived d;
d.myfunction();
return 0;
}
这篇关于C ++:使用基类作为接口的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!