如何将抽象类型数组作为函数参数传递?

web*_*rc2 0 c++ polymorphism inheritance abstract-class parameter-passing

我想定义一个抽象基类,然后传递一个这种类型的数组(显然是一个派生类的实例)作为一个函数参数,但是编译器对我大吼大叫.有任何想法吗?

例如("Testable"是抽象的,"Vecteur"是具体的):

void Testeur::commencerTest(Testable testables[], int nTestables, string titre) {
    cout << "\n" << titre << "\n";
    for (int i=0; i < nTestables; i++) {
        testables[i].afficher();
    }
}

// in main function:
Vecteur v1 = Vecteur(1,2,3);
Vecteur v2 = Vecteur(4,5,6);
Vecteur vecteurs[] = { v1, v2 };
int nVecteurs = 2;

this->commencerTest(vecteurs, nVecteurs, "Some text");
Run Code Online (Sandbox Code Playgroud)

编译器invalid abstract type ‘std::Testable’ for ‘testables’在上面代码的第一行说.

如何将抽象类型数组作为函数参数传递?

Oli*_*rth 5

简短的回答是:你做不到.数组在C++中不是多态的; 这是有充分理由的 - 参见例如什么是对象切片?.请记住,例如arr[i],编译器需要知道每个元素有多大(计算地址偏移量); 通常,对于派生类型,这种计算是错误的.

您考虑使用函数模板,或者可能是(智能)指针的数组/容器.