【问题标题】:Passing an array of pointers to child objects to a function that takes an array of pointers to parent objects将一个指向子对象的指针数组传递给一个函数,该函数接受一个指向父对象的指针数组
【发布时间】: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 类是-a Parent,但Child* 的数组与Parent* 的数组不同。在不知道您的用例或程序应该解决的问题的情况下,也许您真的应该使用 Parent* 的数组?
  • 想想如果该函数执行p[0] = new AnotherChild; 之类的操作会发生什么,其中AnotherChild 是另一个派生自Parent 的类。它会在数组中放置一个无效的指针。

标签: c++ arrays pointers


【解决方案1】:

将一个指向子对象的指针数组传递给一个函数,该函数接受一个指向父对象的指针数组

然后,您需要创建一个 Parent* 数组,并使用 Child*s 填充。

例子:

class Parent {
public:
    virtual ~Parent() = default;
};

class Child : public Parent {};

void func(Parent *p[]) {
    //something
}

int main() {
    Parent *c[10] {
        new Child, new Child, new Child,
        new Child, new Child, new Child,
        new Child, new Child, new Child,
        new Child,
    };
    
    func(c);
    
    for(auto p : c) delete p;
}

一个更好的选择可能是使用包含unique_ptr<Parent>vector(或std::array),当您完成对象时不必delete

#include <iostream>
#include <memory>
#include <vector>

class Parent {
public:
    virtual ~Parent() = default;

    virtual void foo() const { std::cout << "Parent\n"; }
};

class Child : public Parent {
public:
    void foo() const override { std::cout << "Child\n"; }
};

void func(std::vector<std::unique_ptr<Parent>>& p) {
    for(auto& ptr : p) ptr->foo();                   // prints Child 10 times
}

int main() {
    std::vector<std::unique_ptr<Parent>> c(10);

    for(auto& ptr : c) ptr = std::make_unique<Child>();
    
    func(c);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 2015-11-25
    相关资源
    最近更新 更多