cout 和字符串连接

新手上路,请多包涵

我只是在回顾我的 C++。我试图这样做:

 #include <iostream>

using std::cout;
using std::endl;

void printStuff(int x);

int main() {
    printStuff(10);
    return 0;
}

void printStuff(int x) {
    cout << "My favorite number is " + x << endl;
}

问题发生在 printStuff 函数中。当我运行它时,“我最喜欢的数字是”中的前 10 个字符会从输出中省略。输出为“e number is”。这个数字甚至没有出现。

解决这个问题的方法是

void printStuff(int x) {
    cout << "My favorite number is " << x << endl;
}

我想知道计算机/编译器在幕后做什么。

原文由 UnseededAndroid 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 610
1 个回答

在这种情况下,+ 重载运算符不会连接任何字符串,因为 x 是整数。在这种情况下,输出按右值时间移动。所以前 10 个字符不会被打印出来。检查 参考。

如果你会写

cout << "My favorite number is " + std::to_string(x) << endl;

它会起作用的

原文由 Ajay Pal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题