【问题标题】:C++ Abstract type initialisationC++ 抽象类型初始化
【发布时间】:2011-01-16 23:27:26
【问题描述】:

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

界面:

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
    }
}

【问题讨论】:

    标签: c++ inheritance abstract-class


    【解决方案1】:

    你使用抽象类作为指针和引用,所以你会这样做

    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++中只有指针和引用是多态的,所以即使Interface不是抽象的,代码也会因为所谓的切片不正确。

    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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-21
        • 2011-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-30
        • 1970-01-01
        • 2014-10-13
        相关资源
        最近更新 更多