【发布时间】:2018-07-11 09:22:31
【问题描述】:
给定以下代码:
#include <iostream>
#include <vector>
#include <cstring>
#include <cassert>
#include <sstream>
using std::string;
using std::ostream;
using std::cout;
using std::endl;
typedef std::basic_ostringstream<char> ostringstream;
class Format { //error1
const char* str;
ostream& os;
int index;
ostringstream savePrint;
public:
Format(const char* str, ostream& os) :
str(str), os(os), index(0) {
}
~Format() {
os << savePrint.str();
}
template<class T>
Format& operator<<(const T& toPrint) {
while (index < strlen(str) && str[index] != '%') {
savePrint << str[index++];
}
if (index == strlen(str)) {
throw std::exception();
}
assert(str[index] == '%');
savePrint << toPrint;
index++;
return *this;
}
};
class TempFormat {
const char* str;
public:
TempFormat(const char* str) :
str(str) {
}
friend Format operator<<(ostream& os, TempFormat& f) {
return Format(f.str, os); //error2
}
};
TempFormat format(const char* str) {
return TempFormat(str);
}
int main() {
int year = 2018;
string hello = "Hello";
cout << format("% world! The year is %\n") << hello << year; // error3
}
我收到以下错误:
使用已删除的函数 'std::__cxx11::basic_ostringstream<_chart _traits _alloc>::basic_ostringstream(const std::__cxx11::basic_ostringstream<_chart _traits _alloc>&) [with _CharT = char; _Traits = std::char_traits; _Alloc = std::allocator]'
还有:
使用已删除的函数'Format::Format(const Format&)'
还有:
从“TempFormat”类型的右值初始化“TempFormat&”类型的非常量引用无效
谁能解释我为什么会收到这些错误以及如何解决这些错误?
注意:我想通过这段代码实现printf的版本(与%的连接)。
【问题讨论】:
-
为什么不清楚我在问什么?我确切地提到了我的问题。
-
标题可以提供更多信息
-
顺便说一句,您应该考虑在这里为
str成员使用std::string,这样您就不会经常调用strlen,而您可以str.find('%') -
@lhay86 我觉得很好。
-
@PaulSanders 标题最初是“我该如何解决这些错误?”
标签: c++ class c++11 ostream ostringstream