简体   繁体   English

c ++从函数返回类型

[英]c++ return type from function

In this example I want return int nums[40] 在这个例子中我想要返回int nums[40]
How can I do it? 我该怎么做?

<RETURNTYPE> test()
{
    int nums[40];

    for (int i=0; i < 40; i++)
    {
        nums[i] = i + 1;
    }

    return nums;
}

You can't do that. 你不能这样做。 For several reasons (including history, and C compatibility, and the rule that decays arrays to pointers in several important cases) you cannot return a raw array; 由于多种原因(包括历史记录和C兼容性,以及在几个重要情况下将数组衰减到指针的规则),您无法返回原始数组; but you can return a struct (or class ....) containing that array. 但是你可以返回包含该数组的struct (或class ....)。

What you could do in C++11 is to return a std::array<int,40> ; 你在C ++ 11中可以做的是返回一个std::array<int,40> ; it behaves like your thing, but it is a proper class (with all the usual operations you imagine, and iterator stuff too). 它表现得像你的东西,但它是一个合适的类(你想象的所有常用操作,以及迭代器的东西)。 So your code becomes: 所以你的代码变成:

std::array<int,40> test(void) {
  std::array<int,40> nums;
  for (int i=0; i < 40; i++) {
    nums[i] = i + 1;
  }
  return nums;
}

An optimizing compiler (eg g++ -Wall -O2 -std=c++11 .... using a recent GCC ) will optimize that exactly like your hypothetical return type (or like FISOCPP's answer , which is likely to get compiled into the same object code). 优化编译器 (例如g++ -Wall -O2 -std=c++11 ....使用最近的GCC )将优化与您的假设返回类型完全相同(或者像FISOCPP的答案 ,它可能被编译成相同的目标代码)。

If the size (40) can vary at runtime, use std::vector<int> as the type and declare std::vector> nums{40}; 如果size(40)在运行时可能会有所不同,请使用std::vector<int>作为类型并声明std::vector> nums{40}; -then you later could nums.resize(17); - 然后你可以nums.resize(17); and the data would then stay in heap (so there is a tiny performance penalty). 然后数据将保留在堆中(因此性能损失很小)。

The only way to achieve that is to encapsulate your array into a structure (or union - which is not relevant). 实现这一目标的唯一方法是将数组封装到结构(或联合 - 这是不相关的)。

typedef struct { int ra[20]; } rvtyp;

rvtyp test()
{
    int nums[40];

    for (int i=0; i < 40; i++)
    {
        nums[i] = i + 1;
    }

    return *(rvtyp*)&nums;
}

Then you can access your returned value by 'test().ra'. 然后,您可以通过'test()。ra'访问您返回的值。

You need dynamically allocate memory (it is on stack now). 您需要动态分配内存(它现在在堆栈中)。 Return type will be int * then. 返回类型将是int *然后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM