search

Home  >  Q&A  >  body text

c++11 - C++函数中返回数组的引用

using namespace std;
int odd[]  = {1, 3, 5, 7, 9};
int even[] = {0, 2, 4, 6, 8};
decltype(odd) &arrPtr(int i)
{
    return (i % 2) ? odd : even;
}
int main()
{
    auto a = arrPtr(1);
    int b[] = {1, 2, 3, 4};
    int (&c)[4] = b;
    cout << typeid(a).name() << endl;
    cout << typeid(b).name() << endl;
    cout << typeid(c).name() << endl;
    for (int i = 0; i != 5; ++i)
        cout << a[i] << ' ';
    cout << endl;
}

看上面这段代码,其中arrPtr返回一个数组的引用,用来初始化a,b是一个数组,c是b的引用。

但是三者的typeid依次为:

Pi
A4_i
A4_i

此时a的类型检测为整形指针。

诡异的是遍历输出a中元素又能得到正确结果,但是如果用范围迭代for(auto i: a)语句又会报错,貌似是说a里面没有迭代器。

请问一下如何改写使得arrPtr返回数组引用,并且能够使用范围迭代语句?

怪我咯怪我咯2780 days ago660

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 11:28:37

    GCC 4.8.2 and Clang3.4, there are no problems in actual testing. It is recommended to upgrade the compiler.
    Okay, I misread the question. The code lz posted can be compiled, but changing for (int i = 0; i != 5; ++i) to for (auto i: a) won’t work. The reason is obvious:

    In

    auto x=(int[])&..., auto will not generate a reference type, x will not be an "array reference", but a "pointer", so the subsequent for loop is of course wrong.

    It’s easy to write it correctly. You can change this line to auto &a=arrPtr(1), or if you’re more troublesome, write it as decltype(arrPtr(1)) a=arrPtr(1) and you’ll be fine.

    reply
    0
  • Cancelreply