簡體   English   中英

我如何創建一個函數以使用標准整數數組或唯一指針數組而不過載?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM