【问题标题】:Call to deleted constructor of std::__1::ostream error on operator<< overload在 operator<< 重载时调用 std::__1::ostream 错误的已删除构造函数
【发布时间】:2021-11-11 02:30:31
【问题描述】:

我试图让一个函数被识别为friend,但我不知道我做错了什么。我尝试将内容更改为引用并将内容移入和移出命名空间和标头 cpp。我没有注意到为什么这不起作用的罪魁祸首。

我得到的错误是

error: call to deleted constructor of 'std::__1::ostream' (aka 'basic_ostream<char>')
          return output;
                 ^~~~~~

我认为这可能是一个参考问题,或者是我开始时忘记导入的问题。但我什么都想不出来。

namespace N 
{
    class Complex
    {
    public:
        // Contructors
        Complex(double n, double i)
        {
            this->number = n;
            this->imaginary = i;
        }

        Complex()
        {
            this->number = 0;
            this->number = 0;
        }

        // Accessors
        friend ostream operator<< (ostream& os, const Complex& a);

        // Operator Overloads
        Complex operator + (Complex b)
        {
            Complex c;
            c.number = this->number + b.number;
            c.imaginary = this->imaginary + b.imaginary;
            return c;
        }

    private:
        double number;
        double imaginary;
    };

    ostream operator<<(ostream& output, const Complex& a) 
    {
        output << fixed << setprecision(1) << a.number << " + " << a.imaginary << "i";
        return output;
    }
}

【问题讨论】:

  • 注意:现在错误是“调用 std::__1::ostream 的已删除构造函数”
  • 哦,不知道这意味着什么。感谢您的知识
  • 更改问题标题是不够的。标题应该总结问题,并且错误消息中的信息比摘要中的信息要多。整个错误消息应该被逐字复制到问题正文中(因为我冒昧地演示了——但我没有留下行号和字符位置;通常将这些留在粘贴中)。请注意,错误消息通常占用不止一行。在这种情况下,第二行和第三行会准确指出检测到错误的位置,而无需计算行数和字符位置。

标签: c++ class c++11 operator-overloading friend


【解决方案1】:

您需要通过引用返回std::ostream。这意味着你需要

namespace N 
{
    class Complex 
    {
    public:
        friend std::ostream& operator<< (std::ostream& os, const Complex& a);
        //     ^^^^^^^^^^^^^^

    private:
        // ...
    };

    std::ostream& operator<<(std::ostream& output, const Complex& a)
    //^^^^^^^^^^^^
    {
        
        return output << std::fixed << std::setprecision(1) 
                      << a.number << " + " << a.imaginary << "i";
    }
}

这是因为,std::ostream 是不可复制的:

protected:
basic_ostream( const basic_ostream& rhs ) = delete; (2) (since C++11)

当你通过非引用返回时,它将在operator&lt;&lt;中通过复制返回,这需要复制构造函数调用。由于它已被删除,因此您会收到错误消息。

【讨论】:

    猜你喜欢
    • 2017-02-05
    • 2021-11-08
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多