我有一堂课如下:
class foo{
static std::string L[256][256];
public:
//rest of class
};
std::string foo:L[256][256];
我想使用如下函数初始化
L
。
void begin_l(std::string L[256][256]){
//initialization code
}
我尝试创建一个返回
L
的函数来完成此操作,但收到错误 function cannot return array type 'std::string [256][256]'
我怎样才能做到这一点?
您可以使用直接调用的 lambda 函数来完成此操作:
#include <iostream>
#include <array>
#include <string>
#include <iomanip>
// add an alias for readability
using array_2d_of_string_t = std::array<std::array<std::string, 4>, 4>;
class foo
{
public:
//rest of class
static array_2d_of_string_t L;
};
// initialize static variables with a directly
// invoked lambda function. The lambda function will be a nameless
// function so it can only be used to initialize this variable.
array_2d_of_string_t foo::L = []
{
std::size_t count{ 0ul };
array_2d_of_string_t values{};
// loop over all rows in the 2d array
for (auto& row : values)
{
// loop over all the values in the array and assign a value
for (auto& value : row)
{
value = std::to_string(count++);
}
}
return values;
}();
int main()
{
for (auto& row : foo::L)
{
for (auto& value : row)
{
std::cout << std::quoted(value) << " ";
}
std::cout << "\n";
}
return 0;
}