[英]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.