c++中关于运算符重载的问题

来源:百度知道 编辑:UC知道 时间:2024/05/21 08:01:24
想把++重载,下面程序中为什么++不起作用
#include"iostream"
using namespace std;
class complex
{
public:
complex(double r=0.0,double i=0.0)
{
real=r;imag=i;
}
friend complex operator++(complex c1);
void display();
private:
double real;
double imag;
};

complex operator++(complex c1)
{
c1.real++;
return complex(c1.real,c1.imag);
}
void complex::display()
{
cout<<"("<<real<<","<<imag<<")"<<endl;
}

int main()
{
complex c1(5,10),c2(1.5,2.5),c3;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
c1++;
cout<<"c1++=";
c1.display();
return 0;
}

complex operator++(complex c1)
{
c1.real++;
return complex(c1.real,c1.imag);
}

你这个定义有返回值,并且返回值实现了+1操作,但是这个c1是局部变量,对mian中的c1 不影响.而你的main中 c1++; 只是执行了语句,
改一下你就明白了
complex operator++(complex xx)
{
xx.real++;
return complex(xx.real,xx.imag);
}

main 中c1=c1++;
还有办法就是函数形参用引用,或地址

考,悬赏0分!
小气鬼还想得到知识啊

大家都别理他

再看看