将基类型的STL容器转换为派生类型是否可以? [英] Is it ok to cast a STL container with Base type to Derived type?
问题描述
是否可以将STL容器从基本类型转换为派生类型?
例如,我有两个向量。第一个是在Base类的类型,第二个是在Derive类的类型。
Is it ok to cast a STL container from Base type to Derived type ? For example, I have two vectors. First one is in type of a Base class, second is in type of a Derive class.
class Base
{
// Code
};
class Derive : public Base
{
// Code
};
使用
vector<Base*>* vec_base = new vector<Base*>;
// Add some Derive type data to vec_base
vector<Derive*>* vec_derive = (vector<Derive*>*)(vec_base);
// Using elements as Derive pointers. Works fine.
这是否确定? (它工作正常,但我想得到一些意见)。非常感谢你。
Is this ok ? (It works fine, but I wanted to get some comments about this). Thank you very much.
编辑:根据答案更新。
Updating according to the answers.
说,如果我仔细使用该向量,并且不会使用多继承,并且不会插入除Derive类型以外的对象,是否确定? (我猜,不是)
Say, If I use that vector carefully, and will not use with multiple-inheritance and will not insert objects other than Derive type, is it ok ? (I guess, it is not)
非常感谢你的答案。
推荐答案
这绝对不行,并且是c风格的掩码错误的示例之一。
This is definitely not ok, and is one of the examples of c-style casts masking errors. "It works for me" is not indicative of well defined behaviour in this instance.
如果你真的想这样做,我建议:
If you really want to do this I'd suggest:
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class Base
{
// Code
virtual ~Base();
};
class Derrive : public Base
{
// Code
};
Derrive *convert(Base * in) {
// assert here?
return dynamic_cast<Derrive*>(in);
}
int main() {
vector<Base*>* vec_base = new vector<Base*>;
// Add some Derrive type data to vec_base
vector<Derrive*>* vec_derrive = new vector<Derrive*>;
transform(vec_base->begin(), vec_base->end(), back_insert_iterator<vector<Derrive*> >(*vec_derrive), convert);
}
这篇关于将基类型的STL容器转换为派生类型是否可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!