Derivedの配列は Base の配列ではありません。
a を aにアップキャストする必要がある場合は、ポインタの配列を Base に割り当てるか、できればDerived*
a に割り当てる必要があります。Base*
vector<Base*>
vector<Base*> data(100);
// Initialize the elements
for (vector<Base*>::iterator it = data.begin(); it != data.end(); ++it)
{
*it = new Derived;
}
doStuff(data);
// Destroy the elements
for (vector<Base*>::iterator it = data.begin(); it != data.end(); ++it)
{
delete *it;
}
そして、あなたのdoStuff
関数は次のようになります:
void doStuff(const vector<Base*>& data)
{
// Copy the objects, not the pointers
vector<Base*> newdata;
for (vector<Base*>::const_iterator it = data.begin();
it != data.end(); ++it)
{
newdata.push_back((*it)->clone());
}
// Do stuff
// Destroy the copies
for (vector<Base*>::iterator it = newdata.begin();
it != newdata.end(); ++it)
{
delete *it;
}
}
Base
オブジェクトがまたはであるかどうかを知らずにオブジェクトをコピーするには、仮想コンストラクタイディオムDerived
を使用する必要があることに注意してください。次のように変更する必要があります。Base
Derived
struct Base{
...
virtual Base* clone() const { return new Base(*this); }
virtual ~Base() {}
};
struct Derived : public Base {
...
Derived* clone() const { return new Derived(*this); }
};