重载函数打印

Overloaded function print

本文关键字:打印 函数 重载      更新时间:2023-10-16

对于其中一个赋值,我需要创建一个重载函数打印,用于打印数组的一个元素或所有元素。打印整个数组没有问题:

for( int i = 0; i < size; i++)
    cout << list [ i ] <<endl;

但是,如何使相同的功能仅打印一个特定元素?我看到它的方式是询问用户要打印什么,要么是一个元素,要么是所有数字。还是我在这里错过了什么?

打印整个数组

print (const int *arr) const
{
   // code you have written
}

打印特定数组元素

print (const int *arr, const int index)const // overloaded function
{
  // validate index and print arr[index]
   if (index >=0 && index<size)
       cout << *(arr+index)
}

(既然你说的是重载,我假设你使用的是C++。

重载另一个函数的函数不再是同一个函数。在您的情况下,您将需要一个打印一个元素的函数。换句话说,只有一个int

void print(int num)
{ cout << num << endl; }

然后,提供一个重载,该重载采用一个范围并打印它:

(请注意,在区域中,end 元素是指"超过范围末尾的一个",不应打印。

void print(int* begin, int* end)
{
    while (begin != end) {
        cout << *begin << endl;
        // Or if you want to follow correct decomposition design:
        // print(*begin);
        ++begin;
    }
}

两个函数的用法:

int array[3] = {1, 2, 3};
print(array[0]);
print(array, array + 3);