[英]Why is my copy constructor deleted?
Given the following code: 给出以下代码:
#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
}
I get the following errors: 我收到以下错误:
use of deleted function 'std::__cxx11::basic_ostringstream<_CharT, _Traits, _Alloc>::basic_ostringstream(const std::__cxx11::basic_ostringstream<_CharT, _Traits, _Alloc>&) [with _CharT = char; 使用已删除的函数'std :: __ cxx11 :: basic_ostringstream <_CharT,_Traits,_Alloc> :: basic_ostringstream(const std :: __ cxx11 :: basic_ostringstream <_CharT,_Traits,_Alloc>&)[with _CharT = char; _Traits = std::char_traits; _Traits = std :: char_traits; _Alloc = std::allocator]' _Alloc = std :: allocator]'
And: 和:
use of deleted function 'Format::Format(const Format&)' 使用已删除的函数'Format :: Format(const Format&)'
And: 和:
invalid initialization of non-const reference of type 'TempFormat&' from an rvalue of type 'TempFormat' 从'TempFormat'类型的右值初始化'TempFormat&'类型的非const引用
Can someone explain me why I get these errors and how can I fix them? 有人可以解释我为什么会出现这些错误,我该如何解决?
Note: I want by this code to implement version of printf
(with the connection of the %
). 注意:我希望通过此代码实现printf
版本(与%
的连接)。
Fixes: 修正:
#include <sstream> // defines std::basic_ostringstream
// ...
// basic_ostringstream is movable but no copyable.
// Make Format moveable.
Format(Format&&) = default;
// ...
// Cannot bind a reference to a temporary.
// R-value reference is required here.
friend Format operator<<(ostream& os, TempFormat&& f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.