मेरे पास एक कक्षा है जिसमें कई वर्ग इसे विस्तारित करते हैं। मेरे पास कुछ जेनेरिक लाइब्रेरी यूटिलिटीज हैं जो बेस क्लास में वेक्टर युक्त पॉइंटर्स बनाती हैं ताकि कोई भी उप-वर्ग काम करेगा। मैं वेक्टर के सभी तत्वों को एक विशिष्ट बाल वर्ग में कैसे डाल सकता हूं?क्या मैं प्रत्येक तत्व को देखे बिना 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
यह काफी डुप्ली नहीं है - ध्यान दें कि वह 'वेक्टर' से 'वेक्टर ' पर प्रतिलिपि नहीं बना रहा है, लेकिन दूसरी तरफ! –
मुझे लगता है कि वह एक स्वचालित/निहित डाउनकास्ट की तलाश में है! – Abhay