一个简单的输入运算符重载

#include
#include
using namespace std;
class complex{
private:
int real;
int imag;
public:
complex(int r=0,int i=0) :real(i),imag(i){}
~complex(){}
complex operator +(complex&x)
{
real=real+x.real;
imag=imag+x.real;
return *this;
}
complex operator -(complex&x)
{
real=real-x.real;
imag=imag-x.imag;
return *this;
}
complex operator ++() //前置自增不允许有参数,作为类成员
{
real++;
return *this;
}
complex operator ++(int)
{
imag++;
return *this;
}
complex operator =(complex&x)
{
real=x.real;
imag=x.imag;
return *this;
}

void output()
{
    cout<<real<<" "<<imag<<endl;
}
friend istream operator >>(istream&in,complex&x);

};
istream operator >>(istream&in,complex&x)
{
in>>x.real>>x.imag;
return in;
}
int main()
{
complex c(1,1);
complex d(10,10);
complex e;
e=c+d;
e.output();
e=c-d;
e.output();
c++;
c.output();
++c;
c.output();
return 0;
}

**这段代码,报错说重载的函数 return in是尝试引用被删除的函数、这什么鬼?=-=菜鸟一枚,求解答**

对>>的重载返回值类型改成引用类型就行了

 #include <iostream>
using namespace std;
using namespace std;
class complex{
private:
    int real;
    int imag;
public:
    complex(int r=0,int i=0) :real(i),imag(i){}
    ~complex(){}
    complex operator +(complex&x)
    {
        real=real+x.real;
        imag=imag+x.real;
        return *this;
    }
    complex operator -(complex&x)
    {
        real=real-x.real;
        imag=imag-x.imag;
        return *this;
    }
    complex operator ++() //前置自增不允许有参数,作为类成员
    {
        real++;
        return *this;
    }
    complex operator ++(int)
    {
        imag++;
        return *this;
    }
    complex operator =(complex&x)
    {
        real=x.real;
        imag=x.imag;
        return *this;
    }
    void output()
    {
        cout<<real<<" "<<imag<<endl;
    }
    friend istream &operator>>(istream&in,complex&x);
};
istream &operator>>(istream&in,complex&x)
{
    in>>x.real>>x.imag;
    return in;
}
int main()
{
    complex c(1,1);
    complex d(10,10);
    complex e;
    e=c+d;
    e.output();
    e=c-d;
    e.output();
    c++;
    c.output();
    ++c;
    c.output();
    return 0;
}

第一个形参是一个引用,因为不能复制istream对象(在c++中定义的标准输入输出流类istream和ostream,其中拷贝构造函数和赋值操作符函数都被放置在了private部分,且只有声明,没有定义)。
首先因为istream对象不能复制,所以必须是引用;其次引用可以少一次拷贝,提高效率;最后,为了体现连续性,实现连续输入,达到用多个输入操作符操作一个istream对象的效果,如果不是引用,程序返回的时候就会生成新的临时对象