首页 > 代码库 > 运算符重载例题
运算符重载例题
题目一:不用运算符重载,实现两个复数的相加。产生复数对象c1,c2,得到c3=c1+c2,并打印输出c3。
#include <iostream> using namespace std; class complex { public: complex(){real=0;imag=0;} complex(double r,double i):real(r),imag(i){} complex complex_add(complex & c2); void display(); private: double real,imag; }; complex complex::complex_add(complex & c2) { complex c; c.real=real+c2.real;//谁调用就是谁的this c.imag=imag+c2.imag; return c; } void complex::display() { cout<<"("<<real<<","<<imag<<")"<<endl; } int main() { complex c1(3.5,4.5),c2(3.6,4.4),c3; c3=c1.complex_add(c2); c3.display(); return 0; }
运算符重载:
函数类型 operator 运算符名称(形参列表);
operator+运算符名称,可以理解为函数名
complex complex::operator+(complex &c2)
{ return complex(real+c2.real,imag+c2.imag); }
#include <iostream> using namespace std; class complex { public: complex(){real=0;imag=0;} complex(double r,double i):real(r),imag(i){} complex operator+(complex & c2); void display(); private: double real,imag; }; complex complex::operator+(complex & c2) //运算符重载 { return complex(real+c2.real,imag+c2.imag); } void complex::display() //输出 { cout<<"("<<real<<","<<imag<<")"<<endl; } int main() { complex c2(3.6,4.4),c3; c3=complex(3.5,4.5)+c2; c3.display(); return 0; }
运算符重载例题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。