首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法在C++中连接字符串?

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

Stack Overflow用户
提问于 2017-09-21 09:23:55
回答 4查看 180关注 0票数 0

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

代码语言:javascript
复制
void log(std::string s) {
    std::string tag = "main";
    std::cout << tag << " :" << s << std::endl;
}

我试图这样称呼这个方法:

代码语言:javascript
复制
log("direction" << std::to_string(direction) << ", count: " << std::to_string(count));

directioncount是整数。

在红色下划线的<<中,我得到了以下错误:

没有任何运算符<<与这些操作数匹配。操作数类型为const 10 << std::string

我的头中有#include<string>,以确保字符串能够正常工作。

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

C++初学者。我会感谢你的帮助。

EN

回答 4

Stack Overflow用户

发布于 2017-09-21 09:26:18

在您操作字符串时,使用<<操作符替换+,而不是流:

代码语言:javascript
复制
log("direction" + std::to_string(direction) + ", count: " + std::to_string(count));
票数 2
EN

Stack Overflow用户

发布于 2017-09-21 09:26:46

operator<<不用于任意字符串连接-它被称为“输出流操作符”,并且仅在std::ostream上下文中使用。

你说..。

代码语言:javascript
复制
std::cout << tag << " :" << s << std::endl;

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

代码语言:javascript
复制
std::cout.operator<<(tag).operator<<(" :").operator<<(s).operator<<(std::endl);

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

为了连接std::string实例,只需使用operator+

代码语言:javascript
复制
log("direction" + std::to_string(direction) + ", count: " + std::to_string(count));

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

票数 2
EN

Stack Overflow用户

发布于 2017-09-21 09:33:01

如果您决定使用operator<<表示法,则需要一个了解它的对象。

这里有一个这样的对象(我不认为这是个好主意):

代码语言:javascript
复制
#include <string>
#include <sstream>
#include <iostream>

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

struct string_accumulator
{
    std::ostringstream ss;

    template<class T>
    friend string_accumulator& operator<<(string_accumulator& sa, T const& value)
    {
        sa.ss << value;
        return sa;
    }

    template<class T>
    friend string_accumulator& operator<<(string_accumulator&& sa, T const& value)
    {
        return operator<<(sa, value);
    }

    operator std::string () { return ss.str(); }
};

inline auto collect() -> string_accumulator
{
    return string_accumulator();
}

int main()
{
    int direction = 1;
    int count = 1;
    log(collect() << "direction" << std::to_string(direction) << ", count: " << std::to_string(count));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46340157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档