[英]Storing an array in a separate class file
我正在編寫Ludum Dare,我正在嘗試創建一個單獨的類,它會給我一個數組作為函數的返回類型。 我有一個數組設置,但我無法弄清楚如何使返回類型成為一個數組,以便我可以在main函數中使用它。 我將如何返回一個數組並將main.cpp中的變量設置為該數組?
以下是幾個例子,每個例子都有自己的優點:
#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;
}
# 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節
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.