为什么不能使用整数对字符串进行直接转换,却可以按位对字符串进行转换?

时间:2018-07-11 16:48:35

标签: c++ bit-manipulation

string binary = std::bitset<16>(15).to_string();//This cast is valid
int a=5;
string s=a.to_string()//this givees error

这为什么无效? to_string有什么限制吗?

2 个答案:

答案 0 :(得分:6)

int是C ++中的原始类型,而不是类类型,因此,它不定义任何成员函数,例如int::to_string();。您应该尝试将非成员std::string std::to_string(int)用作:string s = std::to_string(a);

编辑:std::bitset 确实定义成员函数to_string(请参阅文档here),该函数仅用于返回表示字符串的成员字符串。位模式,而不是数字作为字符串化整数。如果您确实希望将std::bitset转换为代表数字 std::string,则可以尝试以下操作:

auto bits = std::bitset<16>(15);
std::string s = std::to_string(bits.to_ulong());

答案 1 :(得分:0)

to_stringstd::bitset的成员函数。 to_string没有int成员。

to_string中提供了一个用于数字类型的<string>函数。您将这样使用它:

int a=5;
string s=to_string(a);
相关问题