字符串与整数的连接
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;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为自己提供这个模板:
然后您可以说:
注意,这几乎相当于 Boost 的
lexical_cast
,以及即将推出的标准中的类似功能。另请注意,此函数以性能为代价换取便利性和类型安全。Provide yourself with this template:
You can then say:
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.您可以使用
boost::lexical_cast
< /a> 如下:You could use
boost::lexical_cast
as follows:您已经接受了@unapersson的答案,但为了记录,我会这样做...
它只构造一个流对象,而不是为每次转换创建并丢弃它们,而且它看起来也更好一点。
(这是 C++ 方式 - 没有像其他语言那样通用的“toString”成员,通常我们使用字符串流或一次性函数,如 @unapersson 的答案。)
You've already accepted @unapersson's answer, but for the record I would do this...
It only constructs one stream object instead of creating and throwing them away for each conversion, and it looks a bit nicer too.
(This is the C++ way - there's no general 'toString' member like other languages, generally we use string streams or a one-off function like in @unapersson's answer.)