我是C ++的新手,我正在将std:stringstream
直接传递到另一种方法,如下所示:
static void copy(byte_array src, int end, stringstream sb) {
copy(src, 0, end, sb);
}
它给了我:
没有用于初始化'stringstream'的匹配构造函数(又名'basic_stringstream< char>')
为什么我需要一个构造函数?
答案 0 :(得分:3)
通过值传递需要复制构造函数,并且流对象特别是非复制构造的。您可以通过引用传递流或移动它。
答案 1 :(得分:3)
您不能按值传递流,它们不包含复制构造函数。你应该通过引用传递它们:
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;
}