C++复数中的“++”运算符重载

来源:百度知道 编辑:UC知道 时间:2024/06/14 12:58:53
#include<iostream>
#include<complex>
using namespace std;
void operator++(complex<int> &temp);
//complex<int> operator+=(complex<int> &x,int y);
int main(int argc, char* argv[])
{
complex<int> a(1,2);
cout<<a<<endl;
complex<int> b(2,3);
complex<int> c=a+b;
cout<<c<<endl;
a+=1;
cout<<a<<endl;
++a;
cout<<a<<endl;
return 0;
}
void operator++(complex<int> &temp)
{
temp.real()=temp.real()+1;
temp.imag()=temp.imag()+1;
}
在复数操作里面没有++运算符,我写了个重载函数为什么总会出现这样的编译错误:
D:\tiancai\tiancai.cpp(22) : error C2106: '=' : left operand must be l-value
D:\tiancai\tiancai.cpp(23) : error C2106: '=' : left operand must be l-value
请高手改下!

函数不可以被赋值
照你的意思最后部分应该改成
void operator++(complex<int> &temp)
{
complex<int> temp2(1,1);
temp+=temp2;
}

++不是这么写的

complex & operator++(complex<int> &temp) ;

另外函数体里不能这么写,temp.real()是函数,只有输出,不能被改写的,具体怎么改要看complex类提供了什么函数来修改他的实部和虚部,有没有setreal setimage之类的成员函数?

void operator++(complex<int> &temp)
{
complex<int> tmp(1,1);
temp+=tmp;
}
temp.real()
temp.imag()只是返回一个值
函数不可以被赋值 不可自增的

最好是这样:
complex<int> &operator++(complex<int> &temp)
{
    complex<int> tmp(1,1);
    temp+=tmp;
    return temp;
}