为什么不能使用继承在C ++中实现接口? [英] Why can't I use inheritance to implement an interface in C++?

查看:155
本文介绍了为什么不能使用继承在C ++中实现接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在父类中实现抽象类成员

为什么C ++不让基类实现派生类的继承接口?

考虑这些对象:

struct A
{
    virtual void foo() = 0;
};

struct B
{
    void foo() { /* neat implementation */ }
};

我不知道为什么--compiler-wise-下面的对象被认为是抽象的:

I wonder why --compiler-wise-- the following object is considered abstract:

struct C : B, A
{
    using B::foo; // I tried my best to make the compiler happy
};

编译器不会让我这样做:

The compiler won't let me do this:

A* a = new C;

Visual Studio 2010说:

Visual Studio 2010 says:


'C':由于以下成员,无法实例化抽象类:'void A :: foo(void)':is abstract:see declaration of'A :: foo'

'C' : cannot instantiate abstract class due to following members: 'void A::foo(void)' : is abstract : see declaration of 'A::foo'

g ++ 4.6.3说:

g++ 4.6.3 says:


无法分配抽象类型的物件'C',因为下面的虚函数在'C'中是纯的:virtual void A :: foo()

cannot allocate an object of abstract type ‘C’ because the following virtual functions are pure within ‘C’: virtual void A::foo()

推荐答案


  • 负责为 A :: foo c> ,但与之无关。

  • the responsibility to provide an implementation for A::foo
  • a method B::foo that has the same name and signature as A::foo, but is not related to it in any way

我认为问题很明显。您尝试使用 A 作为等效的C#接口,但没有办法表达这个概念C ++。

I think the problem is obvious. You are trying to use A as the equivalent of a C# interface, but there is no way to express that concept in C++.

现在使用指令在这里也没有帮助,因为它所做的是带$ B :: foo 放入 C 的范围,这意味着它告诉编译器应该考虑 B :: foo C 中遇到后者时,作为解析名称 foo 的候选者不幸的是,这也与实现纯虚拟方法的责任无关。

Now the using directive also does not help here because all it does is bring B::foo into the scope of C, meaning that it tells the compiler it should consider B::foo as a candidate for resolving the name foo when the latter is encountered inside class C. Unfortunately, that's also unrelated to the responsibility of implementing pure virtual methods.

这篇关于为什么不能使用继承在C ++中实现接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆