如何用函数初始化C++类的静态二维std::string数组成员?
问题
我有如下类定义:
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 }
我曾尝试让函数返回数组来实现,但收到错误提示:function cannot return array type 'std::string [256][256]'
请问该如何实现这一需求?
解决方案
方案1:直接传递静态数组给初始化函数
你写的begin_l函数可以直接调用,注意先修正静态数组定义的语法错误(把foo:L改成foo::L),然后在数组定义后调用初始化函数即可:
class foo{ static std::string L[256][256]; public: //rest of class }; // 修正语法错误:使用::访问静态成员 std::string foo::L[256][256]; void begin_l(std::string L[256][256]){ // 示例初始化逻辑 for(int i = 0; i < 256; ++i){ for(int j = 0; j < 256; ++j){ L[i][j] = std::to_string(i) + "," + std::to_string(j); } } } int main(){ // 直接传递静态数组给初始化函数 begin_l(foo::L); return 0; }
这里函数参数std::string L[256][256]会退化为std::string (*L)[256],可以正确接收二维数组的地址,修改的就是静态数组本身的内容。
方案2:将初始化逻辑设为类的静态成员函数
如果希望初始化逻辑和类绑定,可以把初始化函数改成foo的静态成员,这样无需传递参数就能直接访问私有静态数组:
class foo{ static std::string L[256][256]; public: static void init_L(){ // 直接操作内部静态数组 for(int i = 0; i < 256; ++i){ for(int j = 0; j < 256; ++j){ L[i][j] = std::to_string(i) + "-" + std::to_string(j); } } } // rest of class }; std::string foo::L[256][256]; int main(){ foo::init_L(); return 0; }
方案3:用std::array替代原生数组(现代C++推荐)
原生数组无法被直接返回或拷贝,改用std::array可以解决这个限制,还能让代码更安全、灵活:
#include <array> #include <string> class foo{ static std::array<std::array<std::string, 256>, 256> L; public: // rest of class }; // 初始化函数可以直接返回std::array std::array<std::array<std::string, 256>, 256> create_L(){ std::array<std::array<std::string, 256>, 256> arr; for(int i = 0; i < 256; ++i){ for(int j = 0; j < 256; ++j){ arr[i][j] = std::to_string(i) + "|" + std::to_string(j); } } return arr; } // 直接用返回值初始化静态成员,程序启动时自动完成 std::array<std::array<std::string, 256>, 256> foo::L = create_L();
内容的提问来源于stack exchange,提问作者Sam Moldenha
相关产品推荐
相关产品推荐

