C ++:运算符重载 - cout和cin - ostream函数,不能被引用 - 它是一个已删除的函数

时间:2014-07-16 11:02:47

标签: c++

我重载了一个cout和cin opeartor,当我尝试使用它时,它给了我一个这样的错误:

1 IntelliSense: function "std::basic_ostream<_Elem, _Traits>::basic_ostream(const     std::basic_ostream<_Elem, _Traits>::_Myt &) 
[with _Elem=char, _Traits=std::char_traits<char>]" 
(declared at line 84 of "C:\Program   Files (x86)\Microsoft Visual Studio 12.0\VC\include\ostream") cannot be referenced -- it is a deleted function    

这是我班级的头文件:

#pragma once
#include <iostream>

class Point2D
{
private:
    int m_X;
    int m_Y;
public:
    Point2D(): m_X(0), m_Y(0)
    {
    }

    Point2D(int x, int y): m_X(x), m_Y(y)
    {
    }

    friend std::ostream& operator<< (std::ostream out, const Point2D &point)
    {
        out << "(" << point.m_X << "," << point.m_Y << ")" << std::endl;

        return out;
    }

    friend std::istream& operator>> (std::istream in, Point2D &point) 
    {
        in >> point.m_X;
        in >> point.m_Y;

        return in;
    }

    int getX() const { return m_X; }
    int getY() const { return m_Y; }

    ~Point2D();
};

所以,基本上,它只是一个可以返回并设置X和Y坐标的类。我覆盖了<<>>运算符,使事情变得更容易。

但是当我尝试在主函数中使用它时:

#include "stdafx.h"

#include <iostream>
#include "Point2D.h"

using namespace std;

int main(int argc, char * argv[])
{
    Point2D point(7, 7);

    cout << point;  //there's an error here.


    return 0;
}

这一行似乎有错误:

cout << point; 

我究竟做错了什么?

3 个答案:

答案 0 :(得分:5)

错误消息显示ostream无法复制。

friend std::ostream& operator<< (std::ostream out, const Point2D &point)
{
    ...

std::ostream out按值传递:当调用operator <<时,编译器会尝试复制参数。但是,无法复制std::ostream,因此编译失败。

您应该使用参考

friend std::ostream& operator<< (std::ostream &out, const Point2D &point)
{
    ...

friend std::istream& operator>> (std::istream &in, Point2D &point) 
{
    ...

(即使您正在使用某些提供复制的类,您也不应该使用pass-by-val。复制某些对象非常昂贵;)

答案 1 :(得分:2)

也有同样的问题。对于其他人寻找解决方案。错误

function "std::basic_ostream<_Elem, _Traits>::basic_ostream(const std::basic_ostream<_Elem, _Traits> &) [with _Elem=char, _Traits=std::char_traits<char>]" (declared at line 83 of "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include\ostream") cannot be referenced -- it is a deleted function

来自以下行:

std::ostream& operator<< (std::ostream os, const Point2D &point)

对此进行更正,应该没问题:

std::ostream& operator<< (std::ostream &os, const Point2D &point)

答案 2 :(得分:0)

这里的问题在于参数

friend std::ostream& operator<< (std::ostream out, const Point2D &point)

输入参数out是传递值。当编译器尝试按值复制std::ostream变量时,它将失败,从而导致错误。如下所示通过引用传递变量out,它应该清除错误。另外,返回类型是按引用传递的,因此通过执行以下更改,您将返回相同的对象,而不创建新副本。

friend std::ostream& operator<< (std::ostream &out, const Point2D &point)

有用的链接:How to properly overload the << operator for an ostream?