我有一個基類,有幾個類擴展它。我有一些通用庫實用程序創建一個包含指向基類的指針的向量,以便任何子類都可以工作。我如何將矢量的所有元素轉換爲特定的子類?我可以將std :: vector <Animal*>轉換爲std :: vector <Dog*>而不必查看每個元素?
// A method is called that assumes that a vector containing
// Dogs casted to Animal is passed.
void myDogCallback(vector<Animal*> &animals) {
// I want to cast all of the elements of animals to
// be dogs.
vector<Dog*> dogs = castAsDogs(animals);
}
我天真的解決方案將是這個樣子:書面會放了一堆空指針到您的狗矢量當動物載體含有其它動物的專業化
// A method is called that assumes that a vector containing
// Dogs casted to Animal is passed.
void myDogCallback(vector<Animal*> &animals) {
// I want to cast all of the elements of animals to
// be dogs.
vector<Dog*> dogs;
vector<Animal*>::iterator iter;
for (iter = animals.begin(); iter != animals.end(); ++iter) {
dogs.push_back(dynamic_cast<Dog*>(*iter));
}
}
重複:http://stackoverflow.com/questions/902667/stl-container-assignment-和 - 常量指針 – GManNickG 2009-07-24 03:39:32
這是不是很愚蠢 - 請注意,他不是從`矢量`複製到`矢量 `,但反過來! –
2009-07-24 03:45:21