指向子类对象的指针模板数组,作为函数的参数
Template array of pointers to objects of child classes as argument for a function
我有几个类通过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" );
修改也是一样
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类