C++ 返回数组指针简单测试

C++ 返回数组指针简单测试:

#include <iostream>

static const size_t ARR_SIZE = 10;
static int arr[ARR_SIZE];

// 更新数组
#define UPDATE_ARR_DATA(i)    for (size_t j = 0; j < ARR_SIZE; ++j)\
                              {\
                                  arr[j] = j * i;\
                              }\
                              return &arr;

// 遍历数组
#define iterate_arr(arr_ptr)  for (int i = 0; i < ARR_SIZE; ++i)\
                              {\
                                 std::cout << (*arr_ptr)[i] << std::endl;\
                              }

/* (*arr_ptr) 这个先解引用数组,返回的是数组指针。 */

// 返回数组指针的函数
static int(*func(int i))[ARR_SIZE]
{
    UPDATE_ARR_DATA(i)
}

    // typedef 类型别名
typedef int arr_t[ARR_SIZE];
static arr_t* func_t(int i)
{
    UPDATE_ARR_DATA(i)
}

// 新标准别名
using arr_alias = int[ARR_SIZE];
static arr_alias* func_alias(int i)
{
    UPDATE_ARR_DATA(i)
}

// 尾置返回类型 trailing return type
static auto func_trailing(int i) -> int(*)[ARR_SIZE]
{
    UPDATE_ARR_DATA(i)
}

static decltype(arr)* func_decltype(int i)
{
    UPDATE_ARR_DATA(i)
}

int main()
{
    std::cout << std::endl << "/******原始声明******/" << std::endl << std::endl;
    auto v_arr = func(2); // 返回[10]数组的指针
    iterate_arr(v_arr)

    std::cout << std::endl << "/******typedef 别名******/" << std::endl << std::endl;
    auto v_arr_t = func_t(3);
    iterate_arr(v_arr_t)

    std::cout << std::endl << "/******using 别名******/" << std::endl << std::endl;
    auto v_arr_alias = func_t(4);
    iterate_arr(v_arr_alias)

    std::cout << std::endl << "/******尾置返回类型******/" << std::endl << std::endl;
    auto v_arr_trail = func_trailing(5);
    iterate_arr(v_arr_trail)

    std::cout << std::endl << "/******decltype******/" << std::endl << std::endl;
    auto v_arr_decltype = func_decltype(6);
    iterate_arr(v_arr_decltype)

    return EXIT_SUCCESS;
}

输出:

/******原始声明******/

0
2
4
6
8
10
12
14
16
18

/******typedef 别名******/

0
3
6
9
12
15
18
21
24
27

/******using 别名******/

0
4
8
12
16
20
24
28
32
36

/******尾置返回类型******/

0
5
10
15
20
25
30
35
40
45

/******decltype******/

0
6
12
18
24
30
36
42
48
54




参考:《C++ Primer》P206
posted @ 2024-07-18 14:19  double64  阅读(1)  评论(0编辑  收藏  举报