如何将抽象类型数组作为函数参数传递
How to pass abstract-typed array as function parameter?
我想定义一个抽象基类,然后将该类型的数组(显然充满了派生类的实例)作为函数参数传递,但编译器对我大喊大叫。有什么想法吗?
例如("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) {
此外,标准库容器是一个很好的解决方案。
相关文章:
- 如何在C++中将迭代器作为函数参数传递
- 为什么我不能将引用作为 std::async 的函数参数传递
- 节点插件 API 将数组作为函数参数传递
- 将字符串数组作为函数参数传递
- 如何通过 C++ 中的函数参数传递初始值设定项列表的固定大小的初始值设定项列表?
- 我可以动态创建新地图并作为函数参数传递吗?
- 将任意模板向量作为函数参数C++传递
- 将函数指针作为函数参数传递的目的
- C++:通过函数参数传递的值给出不同的结果
- 当数组大小在C++中未知时,如何在运行时将对字符串数组的引用作为函数参数传递?
- 通过宏将函数参数传递给函数
- C++:访问作为函数参数传递的双指针数组所指向的变量的值
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将派生类构造函数参数传递给受保护的成员
- 将指向数组的指针作为函数参数传递,这本身就是另一个函数的返回值?
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 如何将派生类作为函数参数传递:如果派生类成员不在父类中怎么办
- 如何将变量作为构造函数参数或函数参数传递
- 当数组对象以函数参数传递时,为什么复制构造函数会自称