各位大侠帮我看一下这题。(运算符重载) 谢了!

ra3 2002-05-14 09:55:39
18.1 定义复数类的加法与减法,使之能够执行下列运算:

Complex a(2,5),b(7,8),c(0,0);
c=a+b;
c=b+5.6;
c=4.1+a;

c=4.1+a 这个我实在是做不好了,谁能告诉我应该怎么做,谢谢了!
...全文
113 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
T34 2002-05-14
  • 打赏
  • 举报
回复
小虫的解是对的,可以再简单一点,省一个constructor
complex(double d1 = 0,double d2 = 0):real(d1),image(d2)
{}
Effective C++的条款19中有一个有理数Rational的例子,说明为什么要这么做
c_antinomy 2002-05-14
  • 打赏
  • 举报
回复
本质上是类型转换的问题(对运算符的重载没有涉及到类型转换):
1.定义构造函数完成转换,这是隐含的:
Complex(T t) : real(T), image(0)
{ }
2.定义类型转换函数,这是显式的:
operator T() const
{
return real;
}

Complex cplTest(3.34);
T tTest = cplTest;
这两种方法互相补充,各有所长。
fangrk 2002-05-14
  • 打赏
  • 举报
回复
Complex operator+(const Complex&T,float F){
return Complex(T.getReal()+F,T.getImag());
}
Complex operator+(float F,const Complex&T){
return Complex(T.getReal()+F,T.getImag());
}
Complex operator-(float F,const Complex&T){
return Complex(F-T.getReal(),T.getImag()*(-1));
}
Complex operator-(const Complex&T,float F){
return Complex(T.getReal()-F,T.getImag());
}
Complex operator+(const Complex&T1,const Complex&T2){
return Complex(T1.getReal()+T2.getReal(),
T1.getImag()+T2.getImag());
}
Complex operator-(const Complex&T1,const Complex&T2){
return Complex(T1.getReal()-T2.getReal(),
T1.getImag()-T2.getImag());
}
earthharp 2002-05-14
  • 打赏
  • 举报
回复
楼上的
kof99th 2002-05-14
  • 打赏
  • 举报
回复
#include <iostream.h>
class complex{
double real,image;//实部,虚部
public:
friend complex operator*(const complex&,const complex&);
friend complex operator+(const complex&,const complex&);
complex(double d):real(d),image(0)
{}
complex(double d1,double d2):real(d1),image(d2)
{}
};

complex operator*(const complex& c1,const complex& c2)
{
return complex(c1.real*c2.real-c1.image*c2.image,
c1.real*c2.image+c1.image*c2.real);
}

complex operator+(const complex& c1,const complex& c2)
{
return complex(c1.real+c2.real,c1.image+c2.image);
}
试试吧
kof99th 2002-05-14
  • 打赏
  • 举报
回复
可以通过重载消除隐式转换。
complex operator(const double&,const complex&);
可以计算c=4.1+a;而不用将4.1转换为complex对象。
lak47 2002-05-14
  • 打赏
  • 举报
回复
加点我的想法
template<class _T> Complex operator+(const Complex&T,_T F){...}
template<class _T> Complex operator+(_T F,const Complex&T){...}
template<class _T> Complex operator-(_T F,const Complex&T){...}
template<class _T> Complex operator-(const Complex&T,_T F){...}

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧