[英]Is there a safer way to concatenate integers to const char?
考虑一个名为 foo 的 class
class foo
{
int i;
operator const char*()
{
char buf[255];
sprintf(buf, "your number is: %i", i);
return buf;
}
};
我想将它转换为 const char*。 最好的方法是什么? 现在我的解决方案通过使用 sprintf 来展示它。 但是恐怕当function返回时,这段代码会被标记为freed,会被覆盖掉……
我也尝试过使用 std::string,我只返回 var.c_str()。 但是当 function 终止 var destructs 时,我只是得到随机 output 到处都是......
我现在只是过度夸大了还是有更好的方法?
注意1:我知道通过返回包含这些东西的 std::string 类型的变量是一个可行的解决方案,但它不会立即被 cout 或 printf 识别(需要强制转换 foo 变量)。
如果我要使用 std::string 转换,
class foo
{
private:
int i;
public:
foo() : i(9) {};
operator std::string()
{
return std::string(std::to_string(i));
}
};
int main()
{
foo bar = foo();
std::cout << bar; // no operator "<<" matches these operands, operand types are: std::ostream << foo
}
您的代码具有未定义的行为,因为它返回指向在操作员退出时超出 scope 的局部变量的指针。 您需要使char[]
缓冲区比操作员的寿命更长。
您可以使缓冲区成为 class 的成员:
class foo {
int i;
char buf[255];
operator const char*() const {
sprintf(buf, "your number is: %i", i);
return buf;
}
};
或者,您可以将缓冲区设为static
:
class foo {
int i;
operator const char*() const {
static char buf[255];
sprintf(buf, "your number is: %i", i);
return buf;
}
};
一个更好的选择是返回一个std::string
代替:
class foo {
int i;
operator std::string() const {
return "your number is: " + std::to_string(i);
}
};
但是你必须转换bar
变量,正如你已经发现的那样:
std::cout << static_cast<std::string>(bar);
或者先将其分配给一个变量:
std::string s = bar;
std::cout << s;
更简洁的解决方案是为foo
定义operator<<
的重载:
class foo {
int i;
void print(std::ostream &out) const {
out << "your number is: " << i;
}
operator std::string() const {
std::ostringstream oss;
print(oss);
return oss.str();
}
};
std::ostream& operator<<(std::ostream &out, const foo &f) {
f.print(out);
return out;
}
std::cout << bar; // now it works!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.