【发布时间】:2021-10-28 13:08:09
【问题描述】:
我想做标题中所说的,但我运行时出现以下错误:
error: invalid conversion from ‘Child**’ to ‘Parent**’ [-fpermissive]
为清楚起见,这是我的 parent.hpp 文件:
#ifndef PARENT
#define PARENT
class Parent
{
//something
};
#endif
这是我的 child.hpp 文件
#ifndef CHILD
#define CHILD
#include "parent.hpp"
class Child : public Parent
{
//something
};
#endif
这是我正在尝试使用的功能:
void func(Parent *p[])
{
//something
}
int main()
{
Child *c[10];
func(c);
}
我想知道为什么会发生这种情况,而当参数是一个简单的指针时却没有,以及如果存在这种解决问题的方法,我如何在不使用模板的情况下使其工作。
【问题讨论】:
-
虽然
Child类是-aParent,但Child*的数组与Parent*的数组不同。在不知道您的用例或程序应该解决的问题的情况下,也许您真的应该使用Parent*的数组? -
想想如果该函数执行
p[0] = new AnotherChild;之类的操作会发生什么,其中AnotherChild是另一个派生自Parent的类。它会在数组中放置一个无效的指针。