zoukankan      html  css  js  c++  java
  • C++ 操作符重载

    1、为什么要使用操作符重载?

    操作符和方法在本质上一样,使用操作符更符合人性化的描述。

    2、操作符重载分为 普通操作符重载和成员操作符重载,区别在于:

      a、普通操作符重载要访问对象的私有成员,因此要设计为friend,而成员操作符重载不需要;

      b、相比于普通操作符重载,成员操作符重载,少了一个形参,因为成员方法总是与对象绑定使用的,被绑定的对象就是操作符的第一个参数;


     示例代码:

     1 #include "StdAfx.h"
     2 
     3 class Point
     4 {
     5 private :
     6     int x;
     7     int y;
     8 
     9 public :
    10     Point ();
    11 
    12     Point(int x,int y);
    13 
    14     void Print()const;
    15 
    16     void Set(int x,int y);
    17 
    18     friend Point operator+(const Point& a, const Point& b);
    19 
    20     friend Point operator+(const Point& a, int b);
    21 
    22     Point operator-(const Point& b)
    23     {
    24         Point s;
    25         s.Set(this->x-b.x, this->y-b.y);
    26         return s;
    27     }
    28 
    29     Point operator-(int b)
    30     {
    31         Point s;
    32         s.Set(this->x-b, this->y-b);
    33         return s;
    34     }
    35 };
    View Code
     1 #include "StdAfx.h"
     2 #include <iostream>
     3 #include "Point.h"
     4 
     5 Point ::Point()
     6 {
     7 }
     8 
     9 Point::Point(int x,int y)
    10 {
    11     this->x = x;
    12     this->y = y;
    13 }
    14 
    15 void Point::Print()const
    16 {
    17     std::cout<<"X:"<<x<<" Y:"<<y<<std::endl;
    18 }
    19 
    20 Point operator+(const Point& a,const Point& b)
    21 {
    22     Point s(a.x+b.x,a.y+b.y);
    23 
    24     return s;
    25 }
    26 
    27 
    28 Point operator+(const Point& a,int b)
    29 {
    30     Point s(a.x+b,a.y+b);
    31 
    32     return s;
    33 }
    34 
    35 void Point::Set(int x,int y)
    36 {
    37     this->x = x;
    38     this->y = y;
    39 }
    View Code
  • 相关阅读:
    简单协议解析
    三刺激值
    74hc595
    色彩理论
    灰度值和强度值概念
    RGB 常用颜色对照表
    IAR注释的快捷键
    visual studio 2015 2017 key vs2015 vs2017密钥
    如何在cmd命令行中查看、修改、删除与添加环境变量
    win cmd 设置代理
  • 原文地址:https://www.cnblogs.com/nzbbody/p/3364086.html
Copyright © 2011-2022 走看看