BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #36635同步于 2010/3/15
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

C++编程问题,求助

wengfh
2010/3/15镜像同步2 回复
#include <iostream> using namespace std; struct Complex{ double real; double imag; //对复数乘除法进行重载 const Complex operator *( Complex &C ); // 复数相乘 const Complex operator /( Complex &C ); // 复数相除 const Complex operator ~(); //复数共轭 }; //复数相乘重载 const Complex Complex::operator *( Complex &C ) { Complex RC; RC.real=this->real*C.real- this->imag*C.imag; // 设置相乘后的实数 RC.imag=this->imag*C.real+this->real*C.imag; // 设置相乘后的虚数 return RC; // 返回想乘后的复数 } //复数相除重载 const Complex Complex::operator /(Complex &C) { Complex RC; RC.real=(this->real*C.real+this->imag*C.imag)/(C.real*C.real+C.imag*C.imag); RC.imag=(this->imag*C.real-this->real*C.imag)/(C.real*C.real+C.imag*C.imag); return RC; } const Complex Complex::operator ~() { Complex RC; RC.real=this->real; RC.imag=-this->imag; return RC; } int main() { struct Complex *a=new struct Complex [2]; a[0].real=1;a[0].imag=1; a[1].real=2;a[1].imag=2; struct Complex b; b.real=1;b.imag=1; struct Complex *c=new struct Complex [2]; for(int i=0;i<2;i++) { c[i]=(~a[i])*b; cout<<b.real<<" "<<b.imag<<endl; cout<<a[i].real<<" "<<a[i].imag<<endl; cout<<c[i].real<<" "<<c[i].imag<<endl; } //--------------------------- delete a; delete c; return 0; } 上面程序主要主要在这句c[i]=(~a[i])*b出问题,不知道怎么回事,哪位大牛帮忙分析一下
订阅后,新回复会通过你的通知中心匿名送达。
2 条回复
wangzb机器人#1 · 2010/3/15
你重载的*两边的数都是Complex &C,~a[i]返回的是const Complex,此时调用*当然会出错,因为找不到合适的*号,一种方法是修改~返回不是const。第二种方法是在for循环里增加一个非const临时变量暂时接收~a[i],再用该变量和b相乘,第三种方法就是修改*的参数,改成const Complex &C,并将~a[i]和b的顺序颠倒相乘。 【 在 wengfh 的大作中提到: 】 : #include <iostream> : using namespace std; : struct Complex{ : ...................
wengfh机器人#2 · 2010/3/15
大牛,谢谢