注册 登录
编程论坛 C++教室

程序出现错误,尝试引用已删除的函数,是怎么回事

y442974010f 发布于 2016-09-16 10:31, 7435 次点击
#include<iostream>
#include<iterator>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;

template<class T>
class My_ostream_iterator :public iterator<output_iterator_tag, T> {
private:
    string sep; //分隔符
    ostream & os;
public:
    My_ostream_iterator(ostream & o, string s) :sep(s), os(o) { }
    void operator ++() { }; // ++只需要有定义即可, 不需要做什么
    My_ostream_iterator & operator * () { return *this; }
    My_ostream_iterator & operator = (const T & val)
    {
        os << val << sep; return *this;
    }
};

int main() {
    int a[4] = { 1,2,3,4 };
    My_ostream_iterator<int> oit(cout, "*");
    copy(a, a + 4, oit); //输出 1*2*3*4*
    return 0;
}

程序出现了错误,错误是:
    C2280    “My_ostream_iterator<int> &My_ostream_iterator<int>::operator =(const My_ostream_iterator<int> &)”: 尝试引用已删除的函数    ConsoleApplication4    d:\program files (x86)\microsoft visual studio 14.0\vc\include\xutility    458

请教各个大神这是怎么回事??
4 回复
#2
rjsp2016-09-16 17:17
错了,已删除


[此贴子已经被作者于2016-9-19 08:42编辑过]

#3
y442974010f2016-09-18 16:31
回复 2楼 rjsp
大神你好,我是新手,不是很明白你的意思,可以说得详细一些吗
#4
rjsp2016-09-19 08:29
void operator ++() { };
改为
My_ostream_iterator& operator++() { return *this; }
试试
#5
rjsp2016-09-19 08:50
引用类型是不可以重新引用到别的对象的
所以一旦你的类中有了引用,就没法隐式生成一个 operator= 了

程序代码:
#include <iostream>
using namespace std;

struct foo
{
    const int& value;

    foo( const int& v ) : value(v)
    {
    }

    foo& operator=( const foo& rhs )
    {
        // 你没法让 this->value 重新引用到 rhs.value
        return *this;
    }
};

int main( void )
{
    foo a( 1 );
    foo b( 2 );
    a = b;
    cout << a.value << endl;
    cout << b.value << endl;

    return 0;
}

1