gpt4 book ai didi

c++ - 无法在 C++ 中连接字符串?

转载 作者:行者123 更新时间:2023-11-28 01:43:14 24 4
gpt4 key购买 nike

我有一个使用以下定义记录的方法:

void log(std::string s) {
std::string tag = "main";
std::cout << tag << " :" << s << std::endl;
}

我试图像这样调用这个方法:

log("direction" << std::to_string(direction) << ", count: " << std::to_string(count));

directioncount是整数。

我在使用 << 时遇到以下错误红色下划线:

no operator << matches these operands. operand types are const char [10] << std::string

我有#include<string>在我的标题中,以确保我的字符串正常工作。

我试过了 std::string("direction")问题还是一样。

C++ 初学者。帮助将不胜感激。

最佳答案

operator<<不用于任意字符串连接 - 它称为 “输出流运算符”,并且仅用于 std::ostream 的上下文中.

当你说...

std::cout << tag << " :" << s << std::endl;

...您实际上编写的代码大致相当于:

std::cout.operator<<(tag).operator<<(" :").operator<<(s).operator<<(std::endl);

如你所见operator<<知道如何使用 std::coutstd::string ,但不在字符串之间。


为了连接std::string实例,你可以简单地使用 operator+ :

log("direction" + std::to_string(direction) + ", count: " + std::to_string(count));

请注意,这种串联技术并不是最有效的:您可能需要查看 std::stringstream或者简单地使用 std::string::reserve以避免不必要的内存分配。

关于c++ - 无法在 C++ 中连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46340157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com