c++ cast vector<Inherited*> to vector<abstract*>

荒凉一梦 提交于 2019-12-23 07:47:03

问题


class Interface{};

class Foo: public Interface{};

class Bar{
public:
    vector<Interface*> getStuff();
private:
    vector<Foo*> stuff;
};

How do I implement the function getStuff()?


回答1:


vector<Interface*> result(stuff.begin(), stuff.end());
return result;



回答2:


std::vector<Inherited*> and std::vector<abstract*> are different, and pretty much unrelated, types. You cannot cast from one to the other. But you can std::copy or use iterator range constructor as @Grozz says.

Edit:

Answering your question in the comments: they are different the same way two classes with members of compatible types are different. Example:

struct Foo {
    char* ptr0;
};

struct Bar {
    char* ptr1;
};

Foo foo;
Bar bar = foo; // boom - compile error

For that last statement to work you'd need to define an explicit assignment operator like:

Bar& Bar::operator=( const Foo& foo ) {
    ptr1 = foo.ptr0;
    return *this;
}

Hope this makes it clear.




回答3:


I am using this. It is not very nice, but fast I think :)

vector<Interface*> getStuff()
{
    return *(std::vector<Interface*> *)&stuff;
}

And you can also return only reference to the vector with this method

vector<Interface*> &getStuff()
{
    return *(std::vector<Interface*> *)&stuff;
}


来源:https://stackoverflow.com/questions/3891529/c-cast-vectorinherited-to-vectorabstract

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!