[英]How do i create a function to use a standard integer array or a unique pointer array without overloading?
我正在尝试创建一个程序,该程序创建一个特定大小的数组,然后将该数组扩展一个。 它还需要在函数调用之前显示第一个数组,并在函数调用之后显示新数组。
#include <iostream>
#include <memory>
using namespace std;
unique_ptr<int[]> newCopy(int arry[], int items)
{
unique_ptr<int[]> p(new int[items + 1]);
p[0] = 0;
for (int i = 0; i < items; i++)
{
p[i + 1] = arry[i];
}
return p;
}
void displayArry(int arry[], int items)
{
for (int i = 0; i < items; i++)
{
cout << arry[i] << " ";
}
cout << endl;
}
int main()
{
const int SIZE = 5;
int myNumbers[SIZE] = {18, 27, 3, 14, 95};
displayArry(myNumbers, SIZE);
unique_ptr<int[]> newArry = newCopy(myNumbers, SIZE);
//displayArry(newArry, SIZE + 1);
for (int i = 0; i < SIZE+1; i++)
{
cout << newArry[i] << " ";
}
return 0;
}
我希望display函数显示正常的整数数组和智能指针数组,而不必重载该函数。
显示功能大部分仅适用于标准整数数组。 如果我在主函数内部使用for循环,则扩展函数将起作用,并且新的唯一指针数组将显示正确的值,但是我似乎无法弄清楚如何在显示函数中使用这两个函数。
我已经弄明白了通过不同的传递方法。
首先,我将数组的displayArray()参数更改为带有*的引用。
void displayArry(int arry[], int items)
更改为
void displayArry(int* arry, int items)
然后我将.get()添加到unique_ptr数组的末尾,如下所示:
displayArry(newArry, SIZE + 1);
更改为:
displayArry(newArry.get(), SIZE + 1);
这使我可以通过引用该函数传递所有数据,并允许它正确显示普通数组或unique_ptr数组。
如果对此有任何想法,或者应该做些什么,或者可以做得更好,我将非常感谢您的反馈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.