c++ - 'stringstream' 的初始化没有匹配的构造函数

标签 c++

我是 C++ 的新手,我将 std:stringstream 直接传递给另一个方法,如下所示:

static void copy(byte_array src, int end, stringstream sb) {
    copy(src, 0, end, sb);
}

它给了我:

no matching constructor for initialization of 'stringstream' (aka 'basic_stringstream<char>')

为什么我需要一个构造函数?

最佳答案

您不能按值传递流,它们不包括复制构造函数。您应该通过引用传递它们:

static void copy(byte_array src, int end, stringstream& sb) {
    copy(src, 0, end, sb);
}

[编辑]

有关如何将流传递给函数以对其进行修改的示例:

http://coliru.stacked-crooked.com/a/84e78bdf99575eb4

#include <iostream>
#include <sstream>
#include <algorithm>
#include <functional>
#include <iterator>

// By reference
static void copy1(const char* src, int end, std::stringstream& sb) {
    std::copy(src, src + end, std::ostream_iterator<char>(sb));
}

// By pointer
static void copy2(const char* src, int end, std::stringstream* sb) {
    std::copy(src, src + end, std::ostream_iterator<char>(*sb));
}

// By value, but uses move semantics
static std::stringstream copy3(const char* src, int end, std::stringstream sb) {
    std::copy(src, src + end, std::ostream_iterator<char>(sb));
    return sb;
}

// Actually also by reference but using std::ref
template<typename S>
static void copy4(const char* src, int end, S sb) {
    std::copy(src, src + end, std::ostream_iterator<char>(sb));
}

int main(int argc, char *argv[])
{
    char arr[3] = {'a', 'b', 'c'};
    {
    std::stringstream s;    
    copy1(arr, 3, s);
    std::cout << s.str() << std::endl;
    }

    {
    std::stringstream s;
    copy2(arr, 3, &s);
    std::cout << s.str() << std::endl;
    }

    {
    std::stringstream s;
    s = copy3(arr, 3, std::move(s));
    std::cout << s.str() << std::endl;
    }

    {
    std::stringstream s;
    copy4(arr, 3, std::ref(s));
    std::cout << s.str() << std::endl;
    }    

    return 0;
}

关于c++ - 'stringstream' 的初始化没有匹配的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36365107/

相关文章:

c# - 从 Windows 应用商店应用项目引用 C++ WinRT 组件

c++ - 在哪些情况下不会发生 vtable 构造?

c++ - 从音频中绘制波形的算法

c++ - 在 C++ 中优化字符数组成员交换

C++ : get inherited type from abstract pointer vector

c++ - 多阵列动态内存分配错误

c++ - 这是病毒还是sdk附件?

c++ - 通过引用返回函数调用

c++ - 如何从 Cygwin 构建 Visual Studio 9.0 解决方案并获取构建输出?

c++ - vector 模板冲突声明