zcorvid Asked:2022-06-29 19:01:23 +0000 UTC2022-06-29 19:01:23 +0000 UTC 2022-06-29 19:01:23 +0000 UTC 按条件创建常量字符串 772 有这样的代码: std::string str; if (x > 0) str = "positive"; else if (x < 0) str = "negative"; else str = "zero"; 我想重写代码,str使它成为一个常数。如何让它“漂亮”?创建一个“计算”这个字符串并返回它的函数是很难看的: const std::string str = Foo (); 或者甚至在现场创建一个 lambda ......但你不想 :) 。 c++ строки 5 个回答 Voted Best Answer Harry 2022-06-29T19:21:17Z2022-06-29T19:21:17Z const std::string str = x > 0 ? "positive" : x < 0 ? "negative" : "zero"; 够好吗? user7860670 2022-06-29T19:11:31Z2022-06-29T19:11:31Z 好吧,如果没有函数,那么您可以先在现场设置构造函数参数,然后只创建一个带有const限定符的字符串。 char const * psz_value{}; ::std::size_t value_length{} if (x < 0) { constexpr auto const & sz_value{"negative"} psz_value = sz_value; value_length = ::std::size(sz_value) - 1; } else if (0 == x) { constexpr auto const & sz_value{"zero"} psz_value = sz_value; value_length = ::std::size(sz_value) - 1; } else { constexpr auto const & sz_value{"positive"} psz_value = sz_value; value_length = ::std::size(sz_value) - 1; } ::std::string const str{psz_value, value_length}; 但我通常会将这些行推入表中,而不是每次都重新创建。 AlexGlebe 2022-06-29T19:24:34Z2022-06-29T19:24:34Z 如果它是一个局部变量,那么你可以声明一个额外的常量引用: std::string str_pri; std::string const & str = str_pri ; if (x > 0) str_pri = "positive"; else if (x < 0) str_pri = "negative"; else str_pri = "zero"; 如果它是一个全局变量,那么您可以将工作隐藏变量存储在一个单独的源中,并且只将一个常量引用传输到开放访问。 公共.hpp: extern std::string const & str_pub ; 私人.cpp: static std::string str_pri; std::string const & str_pub = str_pri ; if (x > 0) str_pri = "positive"; else if (x < 0) str_pri = "negative"; else str_pri = "zero"; AR Hovsepyan 2022-06-29T19:31:13Z2022-06-29T19:31:13Z const int i = x < 0 ? -1 : x == 0 ? x : 1; const string p[3] = { "negative", "zero", "positive" }; const string str = p[i + 1]; HolyBlackCat 2022-06-30T01:10:42Z2022-06-30T01:10:42Z 通常,这是通过 lambda 解决的: const std::string str = [&]{ std::string str; // str = ... return str; }(); 但是对于这样一个简单的案例,我会接受哈利的建议? :。
够好吗?
好吧,如果没有函数,那么您可以先在现场设置构造函数参数,然后只创建一个带有
const
限定符的字符串。但我通常会将这些行推入表中,而不是每次都重新创建。
如果它是一个局部变量,那么你可以声明一个额外的常量引用:
如果它是一个全局变量,那么您可以将工作隐藏变量存储在一个单独的源中,并且只将一个常量引用传输到开放访问。
公共.hpp:
私人.cpp:
通常,这是通过 lambda 解决的:
但是对于这样一个简单的案例,我会接受哈利的建议
? :
。