c++ - 将 Child 对象数组传递给接受 Parent* 的函数

标签 c++ c++11 embedded avr-gcc

我在功能有限的嵌入式平台上工作,因此 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/

相关文章:

c++ - 配置文件解析错误

c++ - SWIG_exception() 将 SWIG_RuntimeError 打印为字符串

c++ - 多次调用 make_shared() 时的 shared_ptr 垃圾回收

c++ - 为什么 std::initializer_list 不支持 std::get<>、std::tuple_size 和 std::tuple_element

C++ for-each循环,数组分配在堆上

c++ - 专门化成员指针模板参数解析

c - 如何访问另一个结构体中的结构体字段指针并正确写入?

c++ - 可变参数模板扩展、继承和 std::unique_ptr

c - 我需要有关为微 Controller 编写设备驱动程序的信息

c - 将映射地址声明为外部地址