Abstract class : invalid abstract return type for member function ‘virtual…’

寵の児 提交于 2019-12-05 13:43:44

You cannot return a root by value, since root is abstract and thus there can never exist any values of type root.

You might want to return a pointer:

#include <memory>

std::unique_ptr<root> do_you_feel_lucky(aa const & x, bb const & y)
{
    if (rand() % 2 == 0)
        return { new aa(x) };
    else
        return { new bb(y) };
}

What you have feels a lot like a "clone" or "virtual copy" function, though:

struct Base
{
    virtual std::unique_ptr<Base> clone() const = 0;
};

struct Derived : Base
{
    virtual std::unique_ptr<Base> clone() const
    {
        return { new Derived(*this); }
    }
};

Since you asked about references, here's another thing you could do, though it seems a bit pointless: Pick a reference to one among several derived objects and return a base reference.

root & pick_one_from_two(aa & x, bb & y)
{
    return rand() % 2 == 0 ? x : y;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!