<< C ++中用于字符串的运算符与重载+运算符

捷运

以下两行代码之间是否有区别?

(也许是效率之类的?)

const std::string a = "a";
const std::string b = "b";

std::cout << a << " comes before " << b << "\n";
std::cout << a + " comes before " + b + "\n";
用户975989

是的:

第一行调用operator<<std::cout(的类型std::ostream)。它打印每个操作数。

第二行调用operator+std::string,它创建多个临时std::string对象然后最终调用operator<<它打印它们。

首选第一个,因为它避免了临时对象,并且效果更好。考虑当时的情况ab类型int第一个版本继续工作,第二个版本不再工作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章