C++ C++;抽象类型初始化

C++ C++;抽象类型初始化,c++,inheritance,abstract-class,C++,Inheritance,Abstract Class,我有一个类接口,它有纯虚拟方法。在另一个类中,我有一个嵌套类型,该类型继承自接口并使其非抽象。我使用接口作为类型,并使用函数初始化类型,但由于抽象类型,我无法编译 接口: struct Interface { virtual void something() = 0; } 实施: class AnotherClass { struct DeriveInterface : public Interface { void something() {}

我有一个类接口,它有纯虚拟方法。在另一个类中,我有一个嵌套类型,该类型继承自接口并使其非抽象。我使用接口作为类型,并使用函数初始化类型,但由于抽象类型,我无法编译

接口:

struct Interface
{
   virtual void something() = 0;
}
实施:

class AnotherClass
{
    struct DeriveInterface : public Interface
    {
        void something() {}
    }

    Interface interface() const
    {
        DeriveInterface i;
        return i;
    }
}
用法:

struct Usage : public AnotherClass
{
    void called()
    {
        Interface i = interface(); //causes error
    }
}

您需要在此处使用接口*。

您需要在此处使用接口*。

您使用抽象类作为指针和引用,因此您可以这样做

class AnotherClass
{
    struct DeriveInterface : public Interface
    {
        void something() {}
    }

    DeriveInterface m_intf;

    Interface &interface() const
    {
        return m_intf;
    }
}

struct Usage : public AnotherClass
{
    void called()
    {
        Interface &i = interface();
    }
}
再加上几个分号,就可以了。请注意,只有指针和引用在C++中是多态的,所以即使接口> /COD>不是抽象的,但是由于所谓的切片,代码将是不正确的。
struct Base { virtual int f(); }
struct Der: public Base { 
   int f(); // override
};

...
Der d;
Base b=d; // this object will only have B's behaviour, b.f() would not call Der::f

您使用抽象类作为指针和引用,因此

class AnotherClass
{
    struct DeriveInterface : public Interface
    {
        void something() {}
    }

    DeriveInterface m_intf;

    Interface &interface() const
    {
        return m_intf;
    }
}

struct Usage : public AnotherClass
{
    void called()
    {
        Interface &i = interface();
    }
}
再加上几个分号,就可以了。请注意,只有指针和引用在C++中是多态的,所以即使接口> /COD>不是抽象的,但是由于所谓的切片,代码将是不正确的。
struct Base { virtual int f(); }
struct Der: public Base { 
   int f(); // override
};

...
Der d;
Base b=d; // this object will only have B's behaviour, b.f() would not call Der::f