我在功能有限的嵌入式平台上工作,因此 vector/STL 不可用。
这可能是一个微不足道的问题,但我在 C++ 方面没有太多经验(只有 C 和 C#,这可能使我对明显的 C++ 方法视而不见)。
考虑以下示例:
class Parent {
};
class Child : public Parent {
};
void Test(Parent* parents, uint8_t parentCount) {
// Accessing parent[x] is problematic when 'parents' contains a derived type
}
int main() {
// This is OK
Parent parents[3];
Test(parents, 3);
// This causes problems
Child children[3];
Test(children, 3);
return 0;
}
如果提供指向派生类数组的指针,显然在 Test() 中迭代 parents 是有问题的,因为 的内存占用父级在迭代期间被假定。
我看到的唯一解决方案是传递一个类型为Parent(Parent** parents)的指针数组,但这看起来很麻烦。是否有一些我不知道的 C++ 机制,比如将数组作为引用传递或其他什么?
最佳答案
您可以使用这种方法:
template <class T>
void Test(T* parents, uint8_t parentCount) {
// Code that accesses parent[x]
}
然后像这样使用它:
int main() {
Parent parents[3];
Test(parents, 3);
Child children[3];
Test(children, 3);
return 0;
}
关于c++ - 将 Child 对象数组传递给接受 Parent* 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36914775/