3 回答
The short answer is: you can't. Arrays are not polymorphic in C++; this is for good reason - see e.g. What is object slicing?. Remember that to do e.g. arr[i]
, the compiler needs to know how big each element is (to calculate the address offset); this calculation will be wrong, in general, for derived types.
You consider using a function template, or perhaps an array/container of (smart) pointers.
You can't have an array of objects and then cast it to array of other objects. Think of it, if Vecteur sizeof is 16 and Testable sizeof is 4, how could this even work?
What you want is an array of pointers to objects.
void commencerTest(Testable* testables[], int nTestables)
{
for (int i=0; i < nTestables; i++)
testables[i]->afficher();
}
int main()
{
Testable* vect[10];
for(int i=0; i<10; i++)
vect[i] = new Vecteur();
commencerTest(vect, 10);
}
Try this:
template <typename Type>
void Testeur::commencerTest(Type *testables, int nTestables, string titre) {
The code will eventually complain about not knowing the size of the array. Polymorphism will work through a pointer but not an array as others have noted.
As another possibility, you can use compile-time polymorphism for both type and number for static arrays:
template<typename Type, size_t Num>
void Testeur::commencerTest(Type (&testables)[Num], string titre) {
Also, the standard library containers are a good solution.