C++运算符重载笔记

来源:互联网 发布:喜欢成熟的女人 知乎 编辑:程序博客网 时间:2024/06/02 02:31

今天看了c++中的运算符重载,记录一下,以备后面查看:

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. #include <iostream>
  2. using namespace std;
  3. class F{
  4. int n;
  5. int d;
  6. void reduce(){
  7. int mcd = maxcd(n < 0 ? -n : n, d);
  8. if(mcd != 1){
  9. n /= mcd;
  10. d /= mcd;
  11. }
  12. }
  13. public:
  14. F(int n=0, int d=1):n(n), d(d){
  15. if(d == 0) throw"分母不能为零";
  16. if(d < 0) {
  17. this->d = -this->d;
  18. this->n = -this->n;
  19. }
  20. reduce();
  21. cout << "F(" << n << '/' << d << ")" << endl;
  22. }
  23. static int maxcd(int a,int b){
  24. if(a == 0) return b;
  25. return maxcd(b%a, a);
  26. }
  27. friend ostream& operator<<(ostream& o,const F& f){
  28. o << f.n << '/' << f.d;
  29. return o;
  30. }
  31. friend F operator+(const F& lh,const F& rh){
  32. return F(lh.n * rh.d + lh.d * rh.n, lh.d * rh.d);
  33. }
  34. //成员函数,少一个参数(当前对象作为第一个操作数)
  35. F operator*(const F& rh)const{
  36. //匿名对象
  37. return F(n*rh.n, d*rh.d);
  38. }
  39. friend F operator~(const F& f){
  40. return F(f.d, f.n);
  41. }
  42. bool operator!()const{
  43. return n==0;
  44. }
  45. };
  46. int main(){
  47. F f1;
  48. F f2(3);
  49. F f3(6, 12);
  50. F f4(5, 3);
  51. F f5(2, 9);
  52. cout << f3 << ',' << f4 << endl;
  53. cout << F::maxcd(392, 856) << endl;
  54. cout << f3 + f4 << endl;
  55. cout << f3*f4 << f2 * f3 * f4 << endl;
  56. cout << "~f3 = " << ~f3 << endl;
  57. cout << "!f3 = " << !f3 << endl;
  58. return 0;
  59. }

注意点:

1、匿名对象

2、成员函数和友元函数对运算符重载的区别

3、临时变量只能传给引用常量(const F&),比如f1 + f2 + f3中f1 + f2返回的是一个临时变量

4、友元函数既可以在类内部实现,也可以在类外部实现,不属于类的成员函数

5、const加在方法上则说明该方法内的this指向的对象只能读取不可修改。

0 0