C++中用运算符重载实现复读的运算

秣码厉兵 2019-04-25 08:23:22
#include <iostream.h> class Complex {public: Complex( ){ real=0; imag=0;}//定义一个构造函数。 Complex(int a,int b ) { real=a; imag=b;} Complex(int a){ real=a; imag=0;}//使用Complex方法传递参数。 friend Complex operator+( ){ }; friend Complex operator-( ){ }; friend Complex operator*( ){ }; friend Complex operator/( ){ };//运算符重载函数的声明。 void display( );//函数声明。 private: int real; int imag; } Complex operator+(Complex c1,Complex c2){ return{c1.real+c2.real,c1.imag+c2.imag}; } Complex operator-(Complex c1,Complex c2){ return{c1.real-c2.real,c1.imag-c2.imag}; } Complex operator*(Complex c1,Complex c2){ return{c1.real*c2.real,c1.imag*c2.imag}; } Complex operator/(Complex c1,Complex c2){ return{c1.real+c2.real,c1.imag+c2.imag}; }//运算符重载函数的定义。 viod Complex::display(Complex c1){ cout<<c1.real<<"+"<<c1.imag<<"i"<<endl; } int main( ){ Complex c1(12,8),c2(42,9),sum,minus,product,quotient; sum=c1+c2; minus=c1-c2; product=c1*c2; quotient=c1/c2;//使用重载后的运算符对复数进行运算。 cont<<"c1=";c1.display( ); cont<<"c2=";c2.display( ); cout<<"sum=";sum.display( ); cout<<"minus=";minus.display( ); cout<<"product=";product.display( ); cout<<"quotient="quotient.display( );//输出运算后的值。 return 0; }
...全文
179 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
tongshou 2019-05-06
  • 打赏
  • 举报
回复
不好意思,我的这个表达不准确:
函数定义体 {...} 不要在这里定义。

应该是:
类的成员函数的定义体{...} 只能在 类里、或在类外定义,不能同时在两个地方定义。 即使{...} 里是空的,那也是函数体 定义。
秣码厉兵 2019-05-03
  • 打赏
  • 举报
回复
引用 3 楼 tongshou的回复:
friend Complex operator+( ){ };
==>
friend Complex operator+(Complex &c1, Complex &c2 );

函数定义体 {...} 不要在这里定义。

-----------------------------------------------------------------------

Complex operator+(Complex c1,Complex c2){
return{c1.real+c2.real,c1.imag+c2.imag}; <-----------这里的 {。。。}是什么意思?
}

==>
Complex operator+(Complex &c1,Complex &c2){
return Complex (c1.real+c2.real, c1.imag+c2.imag);
}

为了运行效率,函数的对象型参数应该使用 引用 &,
感谢指正,这里是我马虎了
秣码厉兵 2019-04-26
  • 打赏
  • 举报
回复
引用 1 楼 Italink的回复:
你类内部声明运算符重载,参数没写
嗯,我再改一下
tongshou 2019-04-26
  • 打赏
  • 举报
回复

friend Complex operator+( ){ };
==>
friend Complex operator+(Complex &c1, Complex &c2 );

函数定义体 {...} 不要在这里定义。

-----------------------------------------------------------------------

Complex operator+(Complex c1,Complex c2){
return{c1.real+c2.real,c1.imag+c2.imag}; <-----------这里的 {。。。}是什么意思?
}

==>
Complex operator+(Complex &c1,Complex &c2){
return Complex (c1.real+c2.real, c1.imag+c2.imag);
}

为了运行效率,函数的对象型参数应该使用 引用 &,





Italink 2019-04-25
  • 打赏
  • 举报
回复
你类内部声明运算符重载,参数没写

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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