指向子类对象的指针模板数组,作为函数的参数

Template array of pointers to objects of child classes as argument for a function

本文关键字:参数 函数 数组 子类 对象 指针      更新时间:2023-10-16

我有几个类通过print方法继承了相同的类。我也有一个定制的动态数组模板类。我已经创建了一些动态数组的指针从子类对象。对于每个数组,我都希望有一个单独的函数来调用指针指向的对象的所有打印方法——有时我只想打印"武器",有时只想打印"修改",有时只想打印所有内容。到目前为止,我已经尝试了两种解决方案-复制粘贴每个数组的第一个方法(如代码中所示)或将动态数组转换为指向"母"类的指针数组,并将新数组作为参数传递给通用打印函数。

下面是一些代码:

    class Item {...}
    class Modification : public Item {...}
    class Equipment : public Item {...}
    DynamicArray<Modification*> modification;
    DynamicArray<Equipment*> weapon;
    //The first way:
    void printModsInfo ()
    {
        if (modification.size() == 0)
            cout<<"No mods in inventoryn";
        else
            for (int i = 0; i < modification.size(); i++)
                modification.returnElement(i)->printInfo();
    }
    void printWeaponsInfo ()
    {
        if (weapon.size() == 0)
            cout<<"No weapons in inventoryn";
        else
            for (int i = 0; i < weapon.size(); i++)
                weapon.returnElement(i)->printInfo();
    }
    //The second way:
    void _printModsInfo ()
    {
        Item** tempRef = new Item*[modification.size()];//array of pointers
        for (int i = 0; i < modification.size(); i++)//converting DynamicArray<Modification*> into Item** tempRef
            tempRef[i] = modification.returnElement(i);
        printCertainStuffInInventory (tempRef, modification.size());
        delete tempRef;
    }
    void _printWeaponsInfo ()
    {
    Item** tempRef = new Item*[weapon.size()];
    for (int i = 0; i < weapon.size(); i++)
        tempRef[i] = weapon.returnElement(i);
    printCertainStuffInInventory (tempRef, weapon.size());
    delete tempRef;
    }
    void printCertainStuff (Item** arr, int size)
    {
        if (size == 0)
            cout<<"Nothing from this type in inventory...n";
        else
            for (int i = 0; i < size; i++)
                arr[i]->printInfo();
    }

所以我有两种选择:复制粘贴第一种方法中的五行,或者复制粘贴第二种方法中更复杂的五行,并为打印功能添加另外五行。但我真正想做的是简单地将动态数组作为参数传递,并在打印函数中进行转换(如果需要)-或者通过编写:printCertainStuff(modification);(或"武器"或其他)来简单地调用"打印机"。这也是整个项目设计的要求。我确实咨询了我的老师,但答案是,如果在调用函数之前不转换,就没有办法做到这一点。

但是,仍然有一种方法可以传递这样的动态数组作为参数的方式,我想要的?

我不是100%清楚你想要什么,但如果它是组合你所有的打印方法,你可以尝试使用模板:

template< class T >
void printInfo ( const T& arr, const char* failmessage )
{
    if (arr.size() == 0)
        cout<<failmessage;
    else
        for (int i = 0; i < arr.size(); i++)
            arr.returnElement(i)->printInfo();
}

然后用于武器,你会说:

printInfo( weapon, "No weapons in inventoryn" );

修改也是一样