数组的语法指针C++

C++ syntax pointer for array

本文关键字:C++ 指针 语法 数组      更新时间:2023-10-16

在下面:

int c[10] = {1,2,3,4,5,6,7,8,9,0};
printArray(c, 10);
template< typename T >
void printArray(const T * const array, int count)
{
    for(int i=0; i< count; i++)
        cout << array[i] << " ";
}

我有点困惑为什么模板函数的函数签名没有使用 [] 引用数组是数组,所以像 const T * const[] array .

如何从模板函数签名中判断正在传递数组而不仅仅是非数组变量?

你无法确定。您必须阅读文档和/或从函数参数的名称中找出它。但是由于您正在处理固定大小的数组,因此您可以像这样对其进行编码:

#include  <cstddef> // for std::size_t
template< typename T, std::size_t N >
void printArray(const T (&array)[N])
{
    for(std::size_t i=0; i< N; i++)
        cout << array[i] << " ";
}
int main()
{
  int c[] = {1,2,3,4,5,6,7,8,9,0}; // size is inferred from initializer list
  printArray(c);
}
数组

有一个大小。若要创建对数组的引用,需要静态提供大小。例如:

template <typename T, std::size_t Size>
void printArray(T const (&array)[Size]) {
    ...
}

此函数通过引用获取数组,您可以确定其大小。

您可以尝试如下操作:

template< std::size_t N>
struct ArrayType
{
    typedef int IntType[N];
};
ArrayType<10>::IntType content = {1,2,3,4,5,6,7,8,9,0};
template< std::size_t N >
void printArray(const typename ArrayType<N>::IntType & array)
{
    //for from 0 to N with an array
}
void printArray(const int * & array)
{
    //not an array
}

拉克斯万。