重载函数打印
Overloaded function print
对于其中一个赋值,我需要创建一个重载函数打印,用于打印数组的一个元素或所有元素。打印整个数组没有问题:
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);
相关文章:
- 回溯C++不打印函数,因此文件
- 重写打印函数而不是覆盖基类
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 打印传递给打印函数的矢量
- 如何使用重新定义的打印函数打印Lua表?
- 调用和打印函数,在 C++ 中返回数组
- Lua C API 自定义打印函数,在字符串中传递空格时不调用
- C++二叉树打印函数实现
- 如何从主 C++ 向模板类中的方法发送打印函数
- 如果我不打印函数参数的值,则将其转换为等于零
- 打印函数模板的内容进行类指针
- C++打印函数的结果?
- 打印 C++ 函数
- 编写一个通用打印函数来打印数组
- 用于打印函数进入和退出跟踪的宏
- 每当尝试打印函数变量时,C++ cout 错误
- GDB:当没有可用的名称符号时,如何打印函数参数值
- 在lua中重新定义打印函数时出现问题
- 打印函数会返回一个意外值,原因是什么
- IntStack的C++递归打印函数