C++练习:返回值指针or引用


#include <cstddef>
using std::size_t;

#include <iostream>
using std::cout; using std::endl;

// code to illustrate declarations of array-related types
int arr[10];          // arr is an array of ten ints
int *p1[10];          // p1 is an array of ten pointers
int (*p2)[10] = &arr; // p2 points to an array of ten ints

typedef int arrT[10]; // arrT is a synonym for the type array of ten ints

// two ways to declare function returning pointer to array of ten ints
arrT* func(int i);               // use a type alias
int (*func(int i))[10];          // direct declaration

// two arrays
int odd[] = {1,3,5,7,9};
int even[] = {0,2,4,6,8};

// function that returns a pointer to an int in one of these arrays
int *elemPtr(int i)
{
    // returns a pointer to the first element in one of these arrays
    return (i % 2) ? odd : even;  
}

// returns a pointer to an array of five int elements
//返回一个指针,该指针指向5个int元素构成的数组
int(*arrPtr(int i))[5]
{
    return (i % 2) ? &odd : &even; // returns a pointer to the array 
}

// returns a reference to an array of five int elements
//返回一个由5个int元素构成的数组的引用
int (&arrRef(int i))[5]
{
    return (i % 2) ? odd : even;
}

int main()
{
    int *p = elemPtr(6);         // p points to an int
    int (*arrP)[5] = arrPtr(5);  // arrP points to an array of five ints
    int (&arrR)[5] = arrRef(4);  // arrR refers to an array of five ints

    for (size_t i = 0; i < 5; ++i)
        // p points to an element in an array, which we subscript
        cout << p[i] << endl;  

    for (size_t i = 0; i < 5; ++i)
        // arrP points to an array, 
        // we must dereference the pointer to get the array itself
        cout << (*arrP)[i] << endl;

    for (size_t i = 0; i < 5; ++i)
        // arrR refers to an array, which we can subscript
        cout << arrR[i] << endl;

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值