C ++多继承和纯函数 [英] C++ multiple inheritance and pure functions

查看:176
本文介绍了C ++多继承和纯函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对一个多继承问题感到困惑。考虑下面的代码块:

I'm a bit confused about a "multiple inheritance problem". Consider the following hunk of code:

#include <iostream>

struct iface
{
    virtual void foo () = 0;
    virtual ~iface () {}
};

struct wrapped
{
    virtual void foo ()
    {
        std::cerr << "wrapped\n";
    }
};

struct impl : public wrapped, public iface
{
};

iface* factory ()
{
    return new impl;
}

int main ()
{
    iface *object = factory ();

    object->foo();

    delete object;

    return 0;
}

这是从使用pimpl idiom的代码中抽象出来的。这个想法是, wrapped 是一个复杂的类与各种其他的钟声和口哨。 iface 只是使包裹可见的特定方面和 factory() function通过使用 wrap 构建实现 iface impl $ c>。在我的实际代码中, wrapped 类来自一个带有巨大的头树的库,所以我定义 impl 一个单独的编译单元,以避免我的应用程序的其余部分拉他们。

This is abstracted out of some code that's using the pimpl idiom. The idea is that wrapped is some complicated class with all sorts of other bells and whistles. iface just makes a particular facet of wrapped visible and the factory() function builds an impl class that implements iface by using wrapped. In my real code, the wrapped class comes from a library with an enormous tree of headers, so I define impl in a separate compilation unit to avoid the rest of my application having to pull them in.

无论如何,我粘贴的不编译,并给出以下错误:

Anyway, what I pasted does not compile, and gives the following error:

$ g++ -o test test.cc
test.cc: In function ‘iface* factory()’:
test.cc:23:16: error: cannot allocate an object of abstract type ‘impl’
     return new impl;
                ^
test.cc:17:8: note:   because the following virtual functions are pure within ‘impl’:
 struct impl : public wrapped, public iface
        ^
test.cc:5:18: note:     virtual void iface::foo()
     virtual void foo () = 0;
                  ^

显然,我可以通过编写一个具体的实现<$ c转到 wrapped :: foo()的<$ c> foo 我不明白为什么编译器不从 wrapped 类中选择实现。

Obviously, I can avoid the error by writing a concrete implementation of foo in impl that forwards to wrapped::foo(), but I don't understand why the compiler doesn't pick up the implementation from the wrapped class.

我假设不知何故,从 iface 的foo和从 wrapped 的foo impl ,但我真的不明白为什么。

I assume that somehow the "foo" from iface and the "foo" from wrapped end up being different when doing name resolution (is that the right word) for impl, but I don't really understand why.

推荐答案

如果类的任何虚函数是纯虚函数,那么类是absrtract。
类impl有两个成员函数具有相同的名称

If any virtual function of a class is a pure virtual then the class is absrtract. Class impl has two member functions with the same name

iface::foo

wrapped::foo

类impl的第一个成员函数是纯虚函数,因此类是抽象的。编译器可能不会创建抽象类的对象。

The first member function of class impl is pure virtual, so the class is abstract. The compiler may not create an object of an abstract class.

这篇关于C ++多继承和纯函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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