字符串连接与整数(String Concatenation with Integers)

编程入门 行业动态 更新时间:2024-10-22 08:38:50
字符串连接与整数(String Concatenation with Integers)

Damage和Cost是整数,但正如您在下面的代码中看到的,我想用字符串连接它们(如果这是正确的单词)。 我怎样才能做到这一点?

class Weapon : Shopable{ private: int Damage; public: std::string getDesc() const{ return getName()+"\t"+Damage+"\t"+Cost; } };

Damage and Cost are integers, but as you can see in the code below I want to concatenate them with a string (if that's the right word). How can I do this?

class Weapon : Shopable{ private: int Damage; public: std::string getDesc() const{ return getName()+"\t"+Damage+"\t"+Cost; } };

最满意答案

提供此模板:

#include <sstream> template <class TYPE> std::string Str( const TYPE & t ) { std::ostringstream os; os << t; return os.str(); }

然后你可以说:

return getName() + "\t" + Str( Damage ) + "\t" + Str(Cost);

请注意,这几乎等同于Boost的lexical_cast ,以及即将推出的标准中的类似设施。 另请注意,此功能为了方便和类型安全而交换性能。

Provide yourself with this template:

#include <sstream> template <class TYPE> std::string Str( const TYPE & t ) { std::ostringstream os; os << t; return os.str(); }

You can then say:

return getName() + "\t" + Str( Damage ) + "\t" + Str(Cost);

Note this is pretty much equivalent to Boost's lexical_cast, and to similar facilities in the upcoming standard. Also note that this function trades performance for convenience and type-safety.

更多推荐

本文发布于:2023-08-07 01:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1458456.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   字符串   String   Concatenation   Integers

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!