将数组存储在单独的类文件中

时间:2013-08-24 03:14:45

标签: c++ arrays function class

我正在编写Ludum Dare,我正在尝试创建一个单独的类,它会给我一个数组作为函数的返回类型。我有一个数组设置,但我无法弄清楚如何使返回类型成为一个数组,以便我可以在main函数中使用它。我如何返回一个数组并将main.cpp中的变量设置为该数组?

2 个答案:

答案 0 :(得分:1)

以下是几个例子,每个例子都有各自的优点:

#include <iostream>
// C++11 #include <array>
#include <vector>

void myVectorFunc1(std::vector<int>& data)
{
    for (unsigned i = 0; i < data.size(); ++i)
        data[i] = 9;

    data.push_back(1);
    data.push_back(2);
    data.push_back(3);
}

std::vector<int> myVectorFunc2(void)
{
    std::vector<int> data;
    data.push_back(1);
    data.push_back(2);
    data.push_back(3);
    return data;
}

/* C++ 11

template<std::size_t S>
void myArrayFunc1(std::array<int, S>& arr)
{
    for (auto it = arr.begin(); it != arr.end(); ++it)
        *it = 9;
}

std::array<int,5> myArrayFunc2(void)
{
    std::array<int,5> myArray = { 0, 1, 2, 3, 4 };
    return myArray;
}

*/

int main(int argc, char** argv)
{
    // Method 1: Pass a vector by reference
    std::vector<int> myVector1(10, 2);
    myVectorFunc1(myVector1);

    std::cout << "myVector1: ";
    for (unsigned i = 0; i < myVector1.size(); ++i)
        std::cout << myVector1[i];
    std::cout << std::endl;

    // Method 2: Return a vector
    std::vector<int> myVector2 = myVectorFunc2();

    std::cout << "myVector2: ";
    for (unsigned i = 0; i < myVector2.size(); ++i)
        std::cout << myVector2[i];
    std::cout << std::endl;

    /* C++11

    // Method 3: Pass array by reference
    std::array<int, 3> myArray1;
    std::cout << "myArray1: ";
    myArrayFunc1(myArray1);
    for (auto it = myArray1.begin(); it != myArray1.end(); ++it)
        std::cout << *it;
    std::cout << std::endl;

    // Method 4: Return an array
    std::cout << "myArray2: ";
    std::array<int,5> myArray2 = myArrayFunc2();
    for (auto it = myArray2.begin(); it != myArray2.end(); ++it)
        std::cout << *it;
    std::cout << std::endl;

    */

    return 0;
}

答案 1 :(得分:1)

# include <iostream>
int * func1()
{
   int* array = (int *)malloc(sizeof(int) * 2);
   array[0] = 1;
   array[1] = 5;
   return array;
}
int main()
{
   int * arrayData = func1();
   int len = sizeof(arrayData)/sizeof(int);
   for (int i = 0; i < len; i++)
   {
     std::cout << arrayData[i] << std::endl;
   }
}

请检查https://stackoverflow.com/a/5503643/1903116以了解不执行此操作的原因。并引用该答案

  

函数不应具有类型数组或函数的返回类型,   虽然它们可能有返回类型的指针或引用类型   这样的事情。

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf Page 159 - 第6节