【问题标题】:Why is my copy constructor deleted?为什么我的复制构造函数被删除了?
【发布时间】: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


【解决方案1】:

修复:

#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) 

【讨论】:

  • 谢谢。它修复了错误。你能解释一下是什么问题吗?
  • @Software_t 为您添加了 cmets。
  • 好的,那么&amp;&amp; 如何允许获取对临时的引用?它不是也参考&amp;&amp; 吗?其实&amp;&amp;里面的使用我也看不懂,这是什么意思?
  • @Software_t TempFormat&amp;&amp; 是此处的 r 值参考。阅读en.cppreference.com/w/cpp/language/reference
  • @Caleth return Format(f.str, os) 需要复制构造函数或移动构造函数(在 C++17 之前)。尝试在没有该修复的情况下进行编译。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
相关资源
最近更新 更多