字符串连接与整数(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.
更多推荐
发布评论