博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c++运算符重载
阅读量:4694 次
发布时间:2019-06-09

本文共 1607 字,大约阅读时间需要 5 分钟。

其实c++中各种运算符,都是很特殊的一类函数,运算符函数

不过还是和普通函数有区别的

函数意味着它们可以被重载,这样方便程序员重载一些运算符

说白了,就是你可以自定义这个运算规则

下面是复数类实现加减乘除的运算

加减 用普通成员函数实现

乘除 用友元类成员函数实现

1 #include
2 using namespace std; 3 #define cp Complex 4 5 class Complex 6 { 7 private: 8 double r,i; 9 public:10 Complex(double R = 0,double I = 0):r(R),i(I){};11 //成员函数实现12 Complex operator+(Complex b);13 14 Complex operator-(Complex b);15 16 //友元函数实现17 friend Complex operator*(Complex a,Complex b);18 19 friend Complex operator/(Complex a,Complex b);20 21 void display();22 };23 24 //类外实现函数25 Complex Complex::operator+(Complex b)26 {27 return Complex(r + b.r,i + b.i);28 }29 30 Complex Complex::operator-(Complex b)31 {32 return Complex(r - b.r,i - b.i);33 }34 35 Complex operator*(Complex a,Complex b)36 {37 Complex t;38 t.r = a.r*b.r - a.i*b.i;39 40 t.i = a.r*b.i + b.r*a.i;41 return t;42 }43 44 Complex operator/(Complex a,Complex b)45 {46 Complex t;47 double fm = 1 / (b.r*b.r + b.i*b.i);48 49 t.r = (a.r*b.r + a.i*b.i)*fm;50 t.i = (a.i*b.r - a.r*b.i)*fm;51 return t;52 }53 54 void Complex::display()55 {56 if(i == 0) cout << r << endl;57 else cout << r << ((i > 0)?" + ":"") << i << "i" << endl;58 }59 60 void test()61 {62 cp c1(1,2),c2(3,4),c3,c4,c5,c6;63 c3 = c1 + c2;64 c4 = c1 - c2;65 c5 = c1 * c2;66 c6 = c1 / c2;67 68 c1.display();69 c2.display();70 c3.display();71 c4.display();72 c5.display();73 c6.display();74 }75 int main()76 {77 test();78 return 0;79 }

转载于:https://www.cnblogs.com/mch5201314/p/11589682.html

你可能感兴趣的文章
LeetCode - Same Tree
查看>>
Python dict get items pop update
查看>>
[置顶] 程序员必知(二):位图(bitmap)
查看>>
130242014036-(2)-体验敏捷开发
查看>>
constexpr
查看>>
java web线程池
查看>>
Nginx 流量和连接数限制
查看>>
selenium.common.exceptions.WebDriverException: Message: unknown Error: cannot find Chrome binary
查看>>
iOS - 单例传值 (一)
查看>>
课堂作业1
查看>>
IE8/9 本地预览上传图片
查看>>
Summary of CRM 2011 plug-in
查看>>
Eclipse+Maven环境下java.lang.OutOfMemoryError: PermGen space及其解决方法
查看>>
安全漏洞之Java
查看>>
Oracle 组函数count()
查看>>
Session的使用过程中应注意的一个小问题
查看>>
SDK,API,DLL名词解释
查看>>
试探算法
查看>>
安恒杯七月赛题
查看>>
世界著名logo设计文化解读
查看>>