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

How to pass abstract-typed array as function parameter?

本文关键字:函数 参数传递 数组 类型 抽象 抽象类      更新时间:2023-10-16

我想定义一个抽象基类,然后将该类型的数组(显然充满了派生类的实例)作为函数参数传递,但编译器对我大喊大叫。有什么想法吗?

例如("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");

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

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

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

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

不能有一个对象数组,然后将其强制转换为其他对象的数组。想想看,如果 Vecteur sizeof 是 16,可测试的大小是 4,这怎么可能起作用?

你想要的是指向对象的指针数组。

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);
}

试试这个:

template <typename Type>
  void Testeur::commencerTest(Type *testables, int nTestables, string titre) {

代码最终会抱怨不知道数组的大小。 多态性将通过指针工作,但不像其他人指出的那样通过数组工作。

作为另一种可能性,您可以对静态数组的类型和数字使用编译时多态性:

template<typename Type, size_t Num>
  void Testeur::commencerTest(Type (&testables)[Num], string titre) {

此外,标准库容器是一个很好的解决方案。